Return Reference in C++

C++ -Return by reference

On this page we will discuss about function return by reference which is used in C++.
In C++, a function can return a reference to a variable. This allows the function to modify the original variable and have those changes reflected outside the function.
Return Reference in C++

Return by Reference in C++

In C++, a reference is a way to refer to an object indirectly. A reference is like an alias, or a nickname, for an existing object. To return a reference, the function definition must include an ampersand (&) after the type of the returned value.

Returning a reference can be useful when you want to avoid making a copy of a large object, or when you want to modify an object that was passed to a function by reference. It also allows you to chain function calls, since the return value of the function can be used as the input to another function.

Syntax

data_type func_name(data_type &var_name){
    // code
    return var_name;
} 

Here,

  • data_type is the return type of the function.
  • func_name is the name of the function.
  • var_name is the parameter which is passed as argument to it.

Algorithm

Step 1: Declare the function to return a reference by including an & symbol in the function’s return type.
Step 2: Inside the function, return a reference to the desired object or variable by using the & symbol before its name.
Step 3: When calling the function, you can use the return value as a reference, which allows you to modify the original object or variable.

Examples

Returning a reference to a global variable:

Run
#include <iostream>
using namespace std;

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

int main() {
  int a = 10;
  int b = 20;
  int &c = max(a, b);  // c is a reference to the larger of a and b

  cout << "c: " << c << endl;  

  c = 30;  // This sets the larger of a and b to 30
  cout << "a: " << a << endl;  
  cout << "b: " << b << endl;  

  return 0;
}

Output:

c: 20
a: 10
b: 30

Returning a reference to an element of an array:

Run
#include <iostream>
using namespace std;

int &getElement(int *arr, int index) {
  return arr[index];
}

int main() {
  int arr[5] = {1, 2, 3, 4, 5};
  getElement(arr, 3) = 10;
  cout << arr[3] << endl;  
  return 0;
}

Output:

10

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription