Methods of Calling Function in C++


In C++ you can call the function using two methods:
(1) Call By Value:
In this method when the function is called it will first check function prototype to see weather the specified function is declared or not. If the function is declared then it will match number of arguments, data type and return type.
Now compiler will creates new variables and copy the value of the arguments in to newly created variable. Thus function works with the newly created variables. So it will not affect the original variables in the calling program.
Using this method we can not alter the value of the original variable.


     

(2) Call By Reference:
In this method when the function is called it will first check function prototype to see weather the specified function is declared or not. If the function is declared then it will match number of arguments, data type and return type.
Now instead of passing value of the variable reference of the variable is passed to the function using the concept of reference variable. Thus function works with the original variable.
Using this method we can alter the value of the original variable.

Example:
#include <iostream.h>
int main()
{
int a,b;
void swap(int &x, int &y);
cout<<"Enter Two Numbers:";
cin>>a>>b;
cout<<"Before Swap\n";
cout<<"A="<<a<<endl<<"B="<<b<<endl;
swap(a,b);
cout<<"After Swap\n";
cout<<"A="<<a<<endl<<"B="<<b;
return 0;
}
void swap (int &x, int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Output:
Enter Two Numbers:
10
20
Before Swap
A=10
B=20
After Swap
A=20
B=10


Return by reference


As we can pass reference of the variable to the function, function can also return a reference of the variable to the calling program.

Example:
#include<iostream.h>
int main()
{
int a,b;
int& min(int &x, int &y);
cout<<"Enter Two Numbers";
cin>>a>>b;
min(a,b)=0;
if(a==0)
cout<<"Value of a is less then b so it is set to 0";
else
cout<<"Value of b is less then a so it is set to 0";
}
int& min(int &x, int &y)
{
if (x < y)
return x;
else
return y;
}
Output:
Enter Two Numbers:
10
20
Value of a is less then b so it is set to 0

In the above program function min returns the reference of the variable to the calling program. It compares two numbers and returns the reference of the variable whose value is minimum. In the main function the function call min(a, b) receives the reference of the variable whose value is minimum and set its value to 0.

Download Projects


Download Programs