Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

return
byref
reference
c++
function

How to return a value by reference in C++

Educative Answers Team

​In addition to passing values to a function by reference, C++ also has the ability to return a value by reference.

svg viewer

Code

Consider the code snippet below where the function returns a value by reference:

#include <iostream>
using namespace std;

// Global variable
string str;

// Note how the function is declared. It returns the
// address of a string (str).
string& test() 
{
  return str;
};

int main()
{
    test() = "The quick brown fox.";
    cout << str;
    return 0;
}

Explanation

  • The return type of the function test is string&. This makes it return a reference to the variable str instead of the variable itself.
  • Note how the function call is used on the left side of the assignment statement on line 16. Since the address of str is returned, it can be assigned a value.
  • This stores “The quick brown fox” into the global variable str.

Note that local variables cannot be returned from a function that is defined to return values by reference.

RELATED TAGS

return
byref
reference
c++
function
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring