Differences between pass by value and pass by reference in C++

C++Server Side ProgrammingProgramming

In C++ we can pass arguments into a function in different ways. These different ways are −

  • Call by Value
  • Call by Reference
  • Call by Address

Sometimes the call by address is referred to as call by reference, but they are different in C++. In call by address, we use pointer variables to send the exact memory address, but in call by reference we pass the reference variable (alias of that variable). This feature is not present in C, there we have to pass the pointer to get that effect. In this section we will see what are the advantages of call by reference over call by value, and where to use them

Call by Value

In call by value, the actual value that is passed as argument is not changed after performing some operation on it. When call by value is used, it creates a copy of that variable into the stack section in memory. When the value is changed, it changes the value of that copy, the actual value remains the same.

Example Code

 Live Demo

#include<iostream>
using namespace std;

void my_function(int x) {
   x = 50;
   cout << "Value of x from my_function: " << x << endl;
}

main() {
   int x = 10;
   my_function(x);
   cout << "Value of x from main function: " << x;
}

Output

Value of x from my_function: 50
Value of x from main function: 10

Call by Reference

In call by reference the actual value that is passed as argument is changed after performing some operation on it. When call by reference is used, it creates a copy of the reference of that variable into the stack section in memory. Is uses a reference to get the value. So when the value is changed using the reference it changes the value of the actual variable.

Example Code

 Live Demo

#include<iostream>
using namespace std;

void my_function(int &x) {
   x = 50;
   cout << "Value of x from my_function: " << x << endl;
}

main() {
   int x = 10;
   my_function(x);
   cout << "Value of x from main function: " << x;
}

Output

Value of x from my_function: 50
Value of x from main function: 50

Where to use Call by reference?

  • The call by reference is mainly used when we want to change the value of the passed argument into the invoker function.

  • One function can return only one value. When we need more than one value from a function, we can pass them as an output argument in this manner.

raja
Published on 02-Apr-2019 08:20:38
Advertisements