![]() |
VOOZH | about |
In C++, function prototype is a function declaration that tells the compiler about the name of the function, its return type and the number and type of parameters. With this information, the compiler ensures that function calls can be linked to the function definition, even if the definition is not available at the time of call.
The general syntax of the function prototype is as follows:
where,
A function prototype can be used at any place instead of function declaration such as when a function is called before it is defined.
In C++, it is not compulsory to provide function prototype in all cases. It is only necessary when the function is defined after its call. The compiler will generate an error or warning depending on the situation.
Consider the following program:
Output
./Solution.cpp: In function 'int main()':
./Solution.cpp:7:21: error: 'square' was not declared in this scope
cout << square(5) << endl;
Explanation: In the above code, we tried to call the square() function before it was declared or defined. Since C++ requires functions to be declared or defined before they are used, this leads to a compilation error. Unlike C, C++ does not assume a default return type of int when the prototype is missing.
Adding the prototype at the top fixes the issue:
25
Here are the key benefits of including function prototypes in your C++ program:
Though the terms "function declaration" and "function prototype" are often used interchangeably, there are subtle differences:
| Function Declaration | Function Prototype |
|---|---|
| Tells the compiler about the existence of a function. | Tells the compiler about the existence and signature of the function. |
| Can include only the function’s name and return type. | Must include function’s name, return type, and parameter types. |
| Typically used in header files to declare functions. | Used to ensure type checking for function calls before definition. |
Example