c++

C++ Return by Reference

In this tutorial, we are going to learn about returning a value by reference, we will also see how to use them in C++ programming.

Apart from passing values by reference, you can also return a value by reference.

Let’s see how.

But before moving ahead it is important that you must know concept of Global variables.

A Global variables in the program is a variable defined outside the function. It has a global scope means it holds its value throughout the lifetime of the program. Hence, it can be accessed throughout the program by any function defined within the program.

#include <iostream>

using namespace std; 

int c = 12; // Global variable 

void test_func(); 

int main() { 
    ... .. ... 
    ... .. ... 
    return 0; 
}
void test_func() {
    ... .. ...
}

In the above example c is a global variable, hence it can be accessed by both the functions, i.e. test_func() and main()

Now back to the topic, let’s see an example of Return a value by Reference in C++.


Example 1:

#include <iostream>

using namespace std;

int number; // Global variable

int& test_func(); // Function declaration

int main() {
    test_func() = 10;
    cout << number;
    return 0;
}

int& test_func() {
    return number;
}

Output :

10

# Explanation :

In the above program, you can see the return type of the function test_func() is int&. We use this return type when we have to return a value by reference.

The function test_func() returns the reference of the variable number.

In other words, return number, doesn’t return value of number, instead it return its reference (address).

On this returned address the value can be assigned in main(), like in our case it is test_func() = 10 .

And hence the value got displayed on screen by cout << number.


Points to ponder :-