What is the purpose of a function prototype in C/C++?

C++CServer Side ProgrammingProgramming

Here we will see what are the purpose of using function prototypes in C or 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
raja
Published on 09-Apr-2019 12:51:04
Advertisements