C++ Calling a Function and Return Statement

Calling a function in C++ programming language

After writing a function in C++, we should call this function to perform the task defined inside function body. We cannot execute the code defined inside function's body unless we call it from another function.

When a function X calls another function Y, program control is transferred to function Y. Function Y performs specific task defined in function's body and when function Y terminates either by return statement or when the last statement of function body executes, program control returns back to the calling function X.

Syntax to Call a Function

function_name(argument1 ,argument2 ,...);

We can call a C++ function just by passing the required parameters along with function name. If function returns a value, then we can store returned value in a variable of same data type.

For Example :
int sum = findSum(2, 3);

Above statement will call a function named findSum and pass 2 and 3 as a parameter. It also stores the return value of findSum function in variable sum.


C++ Example Program to call a Function

#include <iostream>
using namespace std;
 
// Function Defination
int getAreaOfSquare(int side){
   // local variable declaration
   int area;
   area = side*side;
   // Return statement
   return area;
}
 
int main(){
   int side, area;

   cout << "Enter side of square\n";
   cin >> side;
   // Calling getAreaOfSquare function 
   area = getAreaOfSquare(side);
   cout << "Area of Square = " << area;

   return 0;
}

Output
Enter radius of circle
4
Area of Circle = 50.256
In above program, we defined a function "getAreaOfSquare" which takes side of a square as input parameter and return the area of the square. Inside main function, we first take side of square as input from user using cin and then call getAreaOfSquare function(by passing side of square) to get the area of square.

C++ Return Statement

The return statement in C++ language terminates the execution of a function and returns control to the calling function. A return statement can also return a single value to the calling function. The return type of a function is defined in function declaration before the name of the function. It is not necessary that function will always return a value. If a function does not return a value, the return type in the function declaration and definition is defined as void.
If no return statement is found in a function definition, then control automatically goes to the calling function after the last statement of the function body is executed.

Syntax of return Statement in C++

return expression;

Expression is optional. If present, is evaluated and then converted to the return data type specified in function declaration.