C++ Functions
C++ Functions
In order to perform some task, number of statements is grouped together. This group of
statements is called as function in C++ programming.
1. Functions are written in order to make C++ program modular. We can break down the
complex program into the smaller functions.
2. In C++ group of statements is given a particular name called function name. Function is
called from some point of the program
3. C++ program must have at least 1 function and that function should be main.
A C++ function definition consists of a function prototype declaration and a function body.
Return Type: return_type is the type of data that function returns. It is not necessary that
function will always return a value.
Function Name: It is the actual name of the function. The function name and the parameter list
together forms the signature of the function
Parameters: Parameters allow passing arguments to the function from the location where it is
called from. Parameter list is separated by comma
Function Body: The function body contains a collection of statements that define what the
function does.
Example
#include <iostream>
using namespace std;
// function declaration
int sum(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 10;
int b = 20;
int result;
return res;
}
Output:
Sum is: 30
Explanation:
We know that each and every C++ program starts with the main function. In the C++ main
function we have declared the local variable inside the function.
Now after the declaration we need to call the function written by the user to calculate the sum of
the two numbers. So we are now calling the function by passing the two parameters.
Now function will evaluate the addition of the two numbers. After the addition of two numbers
the value will be returned to the calling function. Returned value will be assigned to the variable
result.