Function Prototype - Uses

Uses

In C, if a function is not previously declared and its name occurs in an expression followed by a left parenthesis, it is implicitly declared as a function that returns an int and nothing is assumed about its arguments. In this case the compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems. The following code illustrates a situation in which the behavior of an implicitly declared function is undefined.

#include /* * If this prototype is provided, the compiler will catch the error * in main. If it is omitted, then the error may go unnoticed. */ int fac(int n); /* Prototype */ int main(void) { /* Calling function */ printf("%d\n", fac); /* Error: forgot argument to fac */ return 0; } int fac(int n) { /* Called function Function definition */ if (n == 0) return 1; else return n * fac(n - 1); }

The function "fac" expects an integer argument to be on the stack or in a register when it is called. If the prototype is omitted, the compiler will have no way of enforcing this and "fac" will end up operating on some other datum on the stack (possibly a return address or the value of a variable that is currently not in scope). By including the function prototype, you inform the compiler that the function "fac" takes one integer argument and you enable the compiler to catch these kinds of errors and make the compilation process run smoothly. Please also note that implicit function declarations are removed from the C99 standard, thus omission of at least function prototype will result in compile error.

Read more about this topic:  Function Prototype