C++ Functions



In order to perform some task, number of statements are grouped together. This group of statements is called as function in C++ programming.

C++ Function :

  1. Functions are written in order to make C++ program modular. We can break down the complex program into the smaller chunks.
  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 atleast 1 function and that function should be main.

Syntax of C++ Function Definition :

return_type function_name( parameter list )
{
   body of the function
}

A C++ function definition consists of a function prototype declaration and a function body. All the parts of a function are –

Part Explanation
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.

We will explain all the parts of the function one by one –

Function : Simple 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;
 
   // calling a function to get result.
   result = sum(a, b);
 
   cout << "Sum is : " << result << endl;
 
   return 0;
}
 
// function returning the sum of two numbers
int sum(int num1, int num2) 
{
   // local variable declaration
   int res;
 
   res = num1 + num2;

   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.

// local variable declaration:
int a = 10;
int b = 20;
int result;

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.

result = sum(a, b);

Function definition and function call
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.