Functions are the building blocks of any programming language.
A Function is a self contained block of code with a specific purpose. It has a name that is used to identify and call it for execution. The function name is global, but it is not necessarily unique in C++. Ivor Hoprton.
Declaration of a Function
The standard form of declaration of a function is
1 2 3 4 | return_type function_name(parameters list) { body of the function } |
Structure of a Function
There are two main parts of the function. The function header and the function body.
1 2 3 4 5 6 | int sum(int x, int y) { int ans = 0; //holds the answer that will be returned ans = x + y; //calculate the sum return ans //return the answer } Function Header |
In the first line of the above code
1 | int sum(int x, int y) |
It has three main parts
- The name of the function i.e. sum
- The parameters of the function enclosed in paranthesis
- Return value type i.e. int
Function Body
What ever is written with in { } in the above example is the body of the function.
Function Prototypes
The prototype of a function provides the basic information about a function which tells the compiler that the function is used correctly or not. It contains the same information as the function header contains. The prototype of the function in the above example would be like
1 | int sum (int x, int y); |
The only difference between the header and the prototype is the semicolon ;, there must the a semicolon at the end of the prototype.
Function: Return Statement
The return statement in a function has two main purposes.
- It can be used to exit the function at any time during the exection of a function. e.g. it returns the control back to the calling code.
- It can also be used to return a value.
1 2 3 4 5 6 7 | void ShowData(int m) { for(int i=0;i<m;i++) { cout << "Value of M is = " << m; } } |
This function returns the control back to the calling function when the for loop finishes execution.
Mostly function do not use this method toterminate execution. Most of the functions returns a value on specified conditions. Here is an example that will show how to terminate the function upon some condition.
1 2 3 4 5 6 7 8 9 | int ShowData(int m) { for(int i=0;i<m;i++) { cout << "Value of M is = " << m; if (m == 3) return m; } return 0; } |
This function returns the indicator after its execution. We can have a function which returns the calculated valuse.
1 2 3 4 5 6 | int sum(int x, int y) { int ans = 0; //holds the answer that will be returned ans = x + y; //calculate the sum return ans //return the answer } |