Home  >  Article  >  Backend Development  >  What is the purpose of function prototypes in C/C++?

What is the purpose of function prototypes in C/C++?

WBOY
WBOYforward
2023-09-12 22:33:03820browse

What is the purpose of function prototypes in C/C++?

Here we will understand what is the purpose of using function prototype in C or C. The function prototype is used to tell the compiler the number of parameters and the data types required for the function parameters. It also tells the compiler the return type of the function. Based on this information, the compiler cross-checks the function signature before calling the function. If the function prototype is not mentioned, then the program may compile with some warnings and sometimes generate some strange output.

Problems may arise if a function is called somewhere but its body is not yet defined, but is already defined after the current line. The compiler can't find what the function is and what its signature is. In this case, we need function prototypes. If the function has been defined before, then we don't need a prototype.

Sample 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 shows some warnings like this:

[Warning] conflicting types for &#39;function&#39;
[Note] previous implicit declaration of &#39;function&#39; was here

Now use the function prototype , it performs without any problems.

Sample 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

The above is the detailed content of What is the purpose of function prototypes in C/C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete