Home >>C++ Tutorial >C++ Call By Value & Call By Reference

Difference between the call by value and the call by reference in C++

Difference between the call by value and the call by reference in C++

Call by value Call by reference
A value with no change is passed to the function that can be said to be a copy of the original value. The value's address(reference) is passed to the function.
Modification that are made inside the function does not gets reflected on other functions Modification that are made inside the function does get reflected on the outer side of the functions.
Different memory location will be used to create the actual and the formal arguments Same memory location will be used to create the actual and the formal arguments

Call by value in C++

In call by value, the modification in the original value does not happens. In stack memory location, the value that is being passed to the function by the function parameter is stored locally. If the programmer makes a change in the value of the function parameter then it gets changed only for the current function and the value of the variable inside the caller method like main() remains the same.

Here is an example of the call by value in C++ that will help you understand it better:

#include <iostream>  
using namespace std;  
void demo(int x);  
int main()  
{  
int x = 10;  
demo(x);  
cout << "Value of the x is: " << x<< endl;  
return 0;  
}  
void demo(int x)  
{  
x = 10;  
} 
Output :
Value of the x is: 10

Call by reference in C++

Because of the reference (address) passed by the user, modification in the original happens in call by reference in C++. In order to make the actual and formal arguments share the same address space, the address of the value is generally passed to the function. By doing this, the value that is modified inside the function will be reflected in and out of the function.

Please note that you should have a basic knowledge of the pointers, in order to completely grasp the call by reference in C++.

Here is an example that will clear your concept of this topic:

#include<iostream>  
using namespace std;    
void swap(int *a, int *b)  
{  
 int swap;  
 swap=*a;  
 *a=*b;  
 *b=swap;  
}  
int main()   
{    
 int a=10, b=20;    
 swap(&a, &b);   
 cout<<"The value of a  = "<<a<<endl;  
 cout<<"The value of b= "<<b<<endl;  
 return 0;  
}  
Output :
The value of a after swap = 20
The value of b after swap= 10

No Sidebar ads