A function declaration and a function definition are two important concepts in C++. A declaration tells the compiler that a function exists, while a definition provides the actual implementation of that function.
- A function declaration specifies what the function looks like.
- A function definition specifies how the function works.
Function Declaration
A function declaration (also known as a function prototype) informs the compiler about a function's name, return type, and parameters without providing its implementation. It allows the compiler to recognize the function before its actual definition appears in the program.
- Specifies the function's name, return type, and parameter list.
- Allows the function to be called before its definition in the source code.
Syntax
return_type function_name(parameter_list);
#include <iostream>
using namespace std;
// Function Declaration
int add(int, int);
int main()
{
cout << "Sum = " << add(5, 3);
return 0;
}
// Function Definition
int add(int a, int b)
{
return a + b;
}
Output
Sum = 8
Function Definition
A function definition provides the actual implementation of a function. It contains the executable statements that define what the function does when it is called and must match its declaration.
- Contains the function body, including the logic to be executed.
- Specifies the function's return type, name, and parameters, enabling the function to perform its intended task.
Syntax
return_type function_name(parameter_list){
// Function body
// Statements to be executed
}
#include <iostream>
using namespace std;
// Function Declaration
double calculateArea(double);
int main()
{
double radius = 7;
cout << "Area = " << calculateArea(radius);
return 0;
}
// Function Definition
double calculateArea(double radius)
{
return 3.14159 * radius * radius;
}
Output
Area = 153.938
Difference between Function Declaration and Function Definition
| Function Declaration | Function Definition |
|---|---|
| Declares the existence of a function, providing its name and parameters | Provides the actual implementation of the function, defining what the function does |
| Function Declaration is used to let the compiler know about the existence of such a function so that we don't encounter any Reference Errors. | Function Definition is used to provide the actual implementation of the code which will execute every time the function is called. |
Function Declaration does not include the body of the function. | Function Definition includes the body of the function. |
| Syntax: return_type function_name(paramA, paramB); | Syntax: return_type function_name(paramA, paramB) { Implementation details } |