Examples of Function Definitions

In the following example, ary is an array of two function pointers. Type casting is performed to the values assigned to ary for compatibility:

#include <stdio.h>
 
int func1(void);
void func2(double a);
 
int main(void)
{
   double num;
   int retnum;
   void (*ary[2]) ();
   ary[0] = ((void(*)())func1);
   ary[1] = ((void(*)())func2);
 
   ((int (*)())ary[0])();             /*  calls func1  */
   ((void (*)(double))ary[1])(num);   /*  calls func2  */
 
}
 
int func1(void)
{
   int number=3;
   return number;
}
 
void func2(double a)
{
   a=333.3333;
}

The following example is a complete definition of the function sum:

int sum(int x,int y)
{
   return(x + y);
}

The function sum has external linkage, returns an object that has type int, and has two parameters of type int declared as x and y. The function body contains a single statement that returns the sum of x and y.


The following example contains a function declarator sort with table declared as a pointer to int, and length declared as type int. Note that arrays as parameters are implicitly converted to a pointer to the type.

void sort(int table[], int length)
{
   int i, j, temp;

   for (i = 0; i < length - 1; i++)
      for (j = i + 1; j < length; j++)
         if (table[i] > table[j])
         {
            temp = table[i];
            table[i] = table[j];
            table[j] = temp;
         }
}

The following examples contain prototype function declarators:

double square(float x);
int area(int x, int y);
static char *search(char);

The following example shows how a typedef function can be used in a function declarator:

typedef struct tm_fmt { int minutes;
                        int hours;
                        char am_pm;
                      } struct_t;
long time_seconds(struct_t arrival)

The following function set_date declares a pointer to a structure of type date as a parameter. date_ptr has the storage class specifier register.

set_date(register struct date *date_ptr)
{
   date_ptr->mon = 12;
   date_ptr->day = 25;
   date_ptr->year = 87;
}


Functions
Function Calls


main() Function
Function Declarations
Function Definitions
Examples of Function Calls
Example of the main() Function
Examples of Function Declarations