In order to use a function in a program, the function must be first defined somewhere in a program. A function definition contains the code that specifies the actions to be performed. The syntax for defining a function is
return_type function_name (parameter_list) //function header { statement 1; /* function body is always specified */ statement 2; /* within the curly braces */ statement N; }
In C++, the function definition consists of two parts, namely, the function header and the function body. The first line of the function definition that specifies the return_type, function_name and parameter_list of the function is known as the function header, and the sequence of statements that are executed when the function is invoked is known as the function body.
Note that the definition of the function can appear either before main () or after it. In case, the function definition appears before main (), there is no need for declaring the function as the function definition itself acts as the function declaration. However, if function definition appears after main (), the function needs to be declared explicitly in the program.
To understand the concept of function definition before main (), consider this example.
Example : A code segment without function declaration
#include<iostream> using namespace std; int func(int x,float y) //function definition { //function body } int main() { //body of main () }
In this example since func () is defined before main (), it need not to be declared.
To understand the concept of function definition after main (), consider this example.
Example : A code segment with function declaration
#include<iostream> using namespace std; int func(int,float); // function prototype int main () { //body of main ( ) } int func(int x, float y) //function definition { //body of the function }
In this example, since func ( ) is defined after main () , it needs to be declared explicitly in the program.