C++ Function Declaration
A function declaration (also called a function prototype) in C++ tells the compiler about the function’s name, return type, and parameters before its actual definition. It is useful when you want to define the function after the main() function or in a separate file.
Syntax
return_type function_name(parameter_list);
Where:
- return_type – The type of value the function will return (void if it does not return anything).
- function_name – The name of the function.
- parameter_list – Optional list of input parameters the function accepts.
Example of Function Declaration
#include <iostream>
using namespace std;
// Function declaration (prototype)
int add(int a, int b);
int main() {
int sum = add(10, 20); // Function call
cout << "Sum: " << sum << endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Output
Sum: 30
Important Notes
- A function must be declared before it is called if its definition comes after main().
- Function declarations allow the compiler to check for correct usage, such as matching parameters and return types.
- You can declare functions in header files for use across multiple files.
Next Topic
Next, learn about Function Parameters in C++.