Call by Reference in C++

In the call-by-reference method, the memory address (reference) of the actual parameter is passed to the function, allowing direct access and modification of the original values. The actual and the formal parameters point to the same memory address. Any changes made to the parameters within the function are directly reflected in the original values outside the function.

Example of Call by Reference

The below example demonstrates the working of call by reference.

C++




// C++ program to demonstrate the working of call by
// reference
  
#include <iostream>
using namespace std;
  
// function to update the original value
void increment(int& num)
{
    num++;
    cout << num << endl;
}
  
int main()
{
    int number = 5;
    increment(number); // Passing 'number' by reference
    cout << number << endl;
    return 0;
}


Output

6
6

Explanation: In the above code the variable “number” is passed to function increment. A formal parameter “num” points to the same address as “number”. When the function increments the value of the parameter, the changes made in “num” is reflected in “number” as we can see from the output. This is what we say “call by reference”.

Difference Between Call by Value and Call by Reference in C++

In C++ programming we have different ways to pass arguments to functions mainly by Call by Value and Call by Reference method. These two methods differ by the types of values passed through them as parameters.

Before we look into the call-by-value and call-by-reference methods, we first need to know what are actual and formal parameters.

The actual parameters also known as arguments are the parameters that are passed into the function when we make a function call whereas formal parameters are the parameters that we see in the function or method definition i.e. the parameters received by the function.

Similar Reads

Call by Value in C++

In the call-by-value method, function arguments are passed by copying the value of the actual parameter, ensuring the original values remain unchanged. The value is copied to the formal parameter....

Call by Reference in C++

...

Difference between the Call by Value and Call by Reference in C++

In the call-by-reference method, the memory address (reference) of the actual parameter is passed to the function, allowing direct access and modification of the original values. The actual and the formal parameters point to the same memory address. Any changes made to the parameters within the function are directly reflected in the original values outside the function....

Conclusion

...