Explain call by value and call by reference in c++ with example

P.Priyadharshini | 514 Views | c++ | 08 Aug 2016

 

What is a call by value in c++ :

  • In call by value, original value can not be changed or modified. In call by value, when you passed value to the function it is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only but it not change the value of variable inside the caller function such as main().

Call by value flow diagram :

  • Here is the flow diagram describing disassembly steps, call stack and argument variables. Calling swap (a, b) can be split into some assembly steps like

1. Push value of b

2. Push value of a

3. Save return address

4. Call function

Call by value program in c++ :

#include<iostream.h>
#include<conio.h>
void swap(int x, int y)
{
  int temp;
  temp=x;
  x=y;
  y=temp;
}
void main() 
{  
   int x=50, y=60;  
   clrscr();  
   swap(x, y);  // passing value to function
   cout<<"Value of x"<<x;
   cout<<"Value of y"<<y;
   getch();  
}  

Output :

Value of x: 60
Value of y: 50

What is a call by reference in c++ :

  • In call by reference, original value is changed or modified because we pass reference (address). Here, address othe value is passed in the function, so actual and formal arguments shares the same address space. Hence, any value changed inside the function, is reflected inside as well as outside the function.

Call by reference flow diagram in c++ :

  • Here is the flow diagram describing disassembly steps, call stack and argument variables. Calling swap (&a, &b) can be split into some assembly steps like

1. Push value of b

2. Push value of a

3. Save return address

4. Call function

Call by reference program in c++ :

#include<iostream.h>
#include<conio.h>
void swap(int *m, int *n)
{
  int temp;
  temp=*m;
  *m=*n;
  *n=temp;
}
void main() 
{  
  int a=200, n=400;  
  clrscr();  
  swap(&m, &n);  // passing value to function
  cout<<"Value of m"<<m;
  cout<<"Value of n"<<n;
  getch();  
}  

Output :

Value of m: 400
Value of n: 200

Difference between call by value and call by reference :

Call by value

Call by reference

This method copy original value into function as a arguments.

This method copy address of arguments into function as a arguments.

Changes made to the parameter inside the function have no effect on the argument.

Changes made to the parameter affect the argument. Because address is used to access the actual argument.

Actual and formal arguments will be created in different memory location.

Actual and formal arguments will be created in same memory location.