CPP Call: Value & Reference

Calling a function in CPP and passing values to that function can be done in two ways:

  • Call by Value
  • Call by Reference

 

Call by Value Call by Reference
Original value of the function parameter is not modified. Original value of the function parameter is modified.
In this method, we pass a copy of the value to the function. In this method, we pass an address of the value to the function.
The value to be passed to the function is locally stored. The value to be passed to the function is stored at the location same as the address passed.
The value changed inside the function, changes for the current function only. The value changed inside the function, changes for both inside as well as outside the function.
Actual and Formal arguments have unique address spaces. Actual and Formal arguments shares the same address space.

 

Example 1: Example for CPP Call by Value

#include <iostream.h>
using namespace std;
 
int sum(int a, int b)
{
int c;
c = a+b;
return c;
}
 
int main()
{
int x = 100;
int y = 200;
int add;
add = sum(x,y);
cout << x <<" + " << y << " = " << add;
return 0;
}

Output

100 + 200 = 300

Example 2: Example for CPP Call by Reference.

#include <iostream.h>
using namespace std;
 
int sum(int *a, int *b)
{
int *c;
*c = *a + *b;
return *c;
}
 
int main()
{
int x = 100;
int y = 200;
int add;
add = sum(&x,&y);
cout << x <<" + " << y << " = " << add;
return 0;
}

Output

100 + 200 = 300
Please follow and like us:
Content Protection by DMCA.com