Importance of function prototype in C


Here we will see why we should use function prototype in C. The function prototypes are used to tell the compiler about the number of arguments and about the required datatypes of a function parameter, it also tells about the return type of the function. By this information, the compiler cross-checks the function signatures before calling it. If the function prototypes are not mentioned, then the program may be compiled with some warnings, and sometimes generate some strange output.

If some function is called somewhere, but its body is not defined yet, that is defined after the current line, then it may generate problems. The compiler does not find what is the function and what is its signature. In that case, we need to function prototypes. If the function is defined before then we do not need prototypes.

Example Code

#include<stdio.h>
main() {
   function(50);
}
void function(int x) {
   printf("The value of x is: %d", x);
}

Output

The value of x is: 50

This shows the output, but it is showing some warning like below:

[Warning] conflicting types for 'function'
[Note] previous implicit declaration of 'function' was here

Now using function prototypes, it is executing without any problem.

Example Code

#include<stdio.h>
void function(int); //prototype
main() {
   function(50);
}
void function(int x) {
   printf("The value of x is: %d", x);
}

Output

The value of x is: 50

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements