• Home
  • Return by reference in C++ with Examples

Return by reference in C++ with Examples

In C++, you can return a reference from a function. A reference is an alias for a variable, and returning a reference allows you to modify the value of the original variable through the reference.

Here is an example of a function that returns a reference to an integer:

#include <iostream>
using namespace std;

int &max(int &x, int &y)
{
if (x > y)
return x;
else
return y;
}

int main()
{
int a = 5, b = 10;
cout << "Before swap: a = " << a << ", b = " << b << endl;
max(a, b) = 15;
cout << "After swap: a = " << a << ", b = " << b << endl;
return 0;
}

The output of this program will be:

Before swap: a = 5, b = 10
After swap: a = 15, b = 10

In this example, the max() function takes two references to integers as arguments and returns a reference to the larger of the two. When the function is called, the values of the variables a and b are passed to the function, and the reference to the larger variable is returned. The value of the larger variable is then modified using the assignment operator (=).

Returning a reference can be useful when you want to modify the value of a variable in the calling function and have the change reflected in the called function. It can also improve the performance of the program by avoiding the overhead of returning a copy of the value. However, you should be careful when returning a reference, as the reference may become invalid if the original variable goes out of scope or is destroyed.