Tuesday 8 November 2011

Why should I prototype a function? in C programming

Why should I prototype a function?

A function prototype tells the compiler what kind of arguments a function is looking to receive and what
kind of return value a function is going to give back. This approach helps the compiler ensure that calls to
a function are made correctly and that no erroneous type conversions are taking place. For instance, consider
the following prototype:

int some_func(int, char*, long);

Looking at this prototype, the compiler can check all references (including the definition of some_func())
to ensure that three parameters are used (an integer, a character pointer, and then a long integer) and that
a return value of type integer is received. If the compiler finds differences between the prototype and calls
to the function or the definition of the function, an error or a warning can be generated to avoid errors in
your source code. For instance, the following examples would be flagged as incorrect, given the preceding
prototype of some_func():
x = some_func(1); /* not enough arguments passed */
x = some_func(“HELLO!”, 1, “DUDE!”); /* wrong type of arguments used */
x = some_func(1, str, 2879, “T”); /* too many arguments passed */
In the following example, the return value expected from some_func() is not an integer:
long* lValue;
lValue = some_func(1, str, 2879); /* some_func() returns an int,
not a long* */
Using prototypes, the compiler can also ensure that the function definition, or body, is correct and correlates
with the prototype. For instance, the following definition of some_func() is not the same as its prototype,
and it therefore would be flagged by the compiler:
int some_func(char* string, long lValue, int iValue) /* wrong order of
parameters */
{
...
}
The bottom line on prototypes is that you should always include them in your source code because they
provide a good error-checking mechanism to ensure that your functions are being used correctly. Besides,
many of today’s popular compilers give you warnings when compiling if they can’t find a prototype for a
function that is being referenced.

Cross Reference:

VIII.1: When should I declare a function?
VIII.3: How many parameters should a function have?
VIII.4: What is a static function?

No comments:

Post a Comment