Table of Contents
A function definition provides the complete implementation of a function. It specifies the function’s return type, name, parameters, and the statements that are executed when the function is called.
A function definition must contain a function body enclosed in braces. The definition can appear before or after the code that calls the function, provided that a declaration is available before the call when required.
Source Code #
#include <iostream>
int add(int a, int b)
{
return a + b;
}
int main()
{
int result = add(10, 20);
std::cout << "Sum: " << result << '\n';
return 0;
}
Output #
Sum: 30
Explanation #
int add(int a, int b)is the function definition foradd.intspecifies that the function returns an integer value.addis the name of the function.aandbare the function parameters.- The statements enclosed in
{}form the function body. return a + b;calculates the sum and returns the result to the caller.add(10, 20)calls the function and passes10and20as arguments.- The returned value is stored in the variable
result. - Because the complete function definition appears before
main(), a separate function declaration is not required in this example. return 0;terminates the program successfully.