6.2 Function Declaration and Function Prototypes

All identifiers in C need to be declared before they are used. This is true for functions as well as variables. 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. This is also called the function prototype.

Note: Older versions of the C language didn't have prototypes, the function declarations only specified the return type and did not list the argument types. Unless your stuck with an old compiler, function declarations should always be prototypes and this book uses the terms interchangeably.

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 reasonably.

The function definition itself can act as an implicit function declaration. This was used in the above example and was why sum was put before main. If the order was reversed the compiler would not recognize sum as a function. To correct this a prototype could be added before main; Example 6-3 does this.

Example 6-3. A simple program with a function prototype

       A simple example of a function prototype allowing the function
       to be used before it is defined.
    #include <stdio.h>
    int sum (int, int);
    main (void)
        int total;
        total = sum (2, 3);
        printf ("Total is %d\n", total);
        return 0;
    sum (int a, int b)
        return a + b;

The prototype gives a lot of information about the function. One, it tells it the return type. Two, 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.

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.

This, and other documents, can be downloaded from http://opencbp.sourceforge.net/.

For questions about the Open C Book Project, read the documentation.