Function Prototypes

All functions in C need to be declared before they are used as it applies to variables and identifiers. For functions the declaration needs to be before the first call of the function. A full declaration includes the return type and the number and type of the arguments.

Function prototypes: are declaration of functions before the function is actually called.

Having the prototype available before the first use of the function allows the compiler to check that the correct number and type of arguments are used in the function call and that the returned value, if any, is being used properly.

The function definition itself can act as an implicit function declaration. This was used in the below example and was why sum was put before main. If the order was reversed the compiler would not recognize sum as a function.

Example 1. A simple program with a function prototype

#include <stdio.h>    
    int sum (int, int); /* Function prototype. */   

    int main (void)
    {
        int total;
    
        total = sum (2, 3);
        printf ("Total is %d\n", total);
    
        return 0;
    }
    
    int sum (int a, int b)
    {
        return a + b;
    }

The prototype gives a lot of information about the function.

  1. It tells the return type.
  2. It tells it how many parameters there are, and what their types are. The actual names of the parameter values ( a and b in our example) can be left in or out of the prototype. Generally, leaving them out leaves you with the flexibility of renaming variables at will (int sum(int , int); )

Prototypes are often in a separate header file which can be included in other C source files that wish to use the functions. The header stdio.h, for example, contains prototypes for the functions scanf and printf. This is why our examples have been including this file, so that the compiler will let us call those functions. The actual code for these functions is kept in a library elsewhere on the system, the header file only says how to interface with the functions.

Leave a comment