English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Return reference

In this article, you will learn how to return values by reference in a function and how to use it effectively in a program.

In C ++In programming, values can be passed to functions not only by referenceFunctionIt can also return values by reference.

To understand this feature, you should understand the following:

Example: Returning by reference

#include <iostream>
using namespace std;
// Global variable
int num;
// Function declaration
int& test();
int main()
{
    test() = 5;
    cout << num;
    return 0;
}
int& test()
{
    return num;
}

Output result

5

In the above program, the return type of the test() function is int&. Therefore, this function returns a reference to the variable num.

The return statement is return num;. Unlike returning by value, this statement does not return the value of num, but returns the variable itself (address).

Therefore, when returningvariableYou can assign a value to it, just like in test()= 5as done in

This will5Store it in the variable num, which is displayed on the screen.

Important things to remember when returning by reference.

  • A regular function returns a value, but this function does not return. Therefore, you cannot return a constant from this function.

    int& test() {
        return 2;
    }
  • You cannot return a local variable from this function.

    int& test()
    {
        int n = 2; 
        return n; 
    }