Call by Value Vs Call by Reference (Difference Between)

Call by Value Vs Call by Reference

  • Sending the values of variables from caller to calle function is called call-by-refernce
  • Any changes made in function defination will not affect in caller fucntion
Call by value vs call by refference
call-by-value-vs-call-by-reference

Example

Run

#include<iostream>
using namespace std; void swap (int, int); int main () //caller function { int a = 2, b = 3; swap (a, b); //fun_call cout << "In calle:after swapping a=" << a << " b=" << b; } void swap (int a, int b) { b = (a + b) - (a = b); //swap logic in a single line /* a+b=5 b=5-(a=3)//a changes to 3 b changes b=5-3=2 */ cout << "In called:after swapping a=" << a << " b=" << b; }

o/p

In calle:after swapping a:2 b:3
In called:after swapping a:3 b:2
  • Here ‘a’ ,’b’ in main function is different from ‘a’,’b’ from swap() function.
  • Just data is copied, both are having different scopes and different memory locations
  • Hence changes in the swap() ‘a’, ‘b’ will not affect the main ‘a’, ‘b’

call by address

  • Sending the address of variables from caller to calle function is called call-by-address
  • Any changes made in function definition will also affect the change in the caller function

Example

Run
#include<iostream>
using namespace std;
void swap(int*,int*);
main()//caller function
{
int a=2,b=3;
swap(&a,&b);//fun_call
cout<<"In called:after swapping a="<<a<<" b="<<b<<endl;//a,b changes
}
void swap(int *c,int *d)
{
*d=(*c+*d)-(*c=*d);//swap logic in a single line
/*
a+b=5
b=5-(a=3)//a changes to 3 b changes b=5-3=2
*/
cout<<"In called:after swapping a="<<a<<" b="<<b<<endl;
}

O/P

In calle: after swapping a:3 b:2
In called: after swapping a:3 b:2
  • In this address of main() ‘a’, ‘b’  is passed to swap() and stored in pointers ‘c’, ‘d’
  • Hence * c,*d points to a,b respectively and having same locations
  • Here a and *c and b and *d both are the same, any changes in either caller or called function will reflect other