Table of Contents
A function declaration, also called a function prototype, informs the compiler about a function before the function is called or defined. It specifies the function’s name, return type, and parameter types.
A function can therefore be declared before main() and defined later in the source file. This allows the compiler to verify function calls even when the complete function definition has not yet been encountered.
Source Code #
#include <iostream>
int add(int, int);
int main()
{
int result = add(10, 20);
std::cout << "Sum: " << result << '\n';
return 0;
}
int add(int a, int b)
{
return a + b;
}
Output #
Sum: 30
Explanation #
int add(int, int);is a function declaration.- The declaration specifies that
addreturns anintand accepts twointparameters. - Parameter names are optional in a function declaration, so only the parameter types are specified.
- The semicolon at the end indicates that this is a declaration rather than a function definition.
main()can calladd()because the compiler has already encountered its declaration.add(10, 20)calls the function with two integer arguments.- The function definition appears after
main(). int add(int a, int b)provides the function’s implementation and names its parameters.return a + b;returns the calculated sum to the caller.- The declaration and definition must have compatible return types and parameter types.