What is Return by Reference in C++

What is Return by Reference in C++

In C++ Programming, not only can you pass values by reference to a function but you can also return a value by reference.
To understand this feature, you should have the knowledge of:
  • Global variables

Example: Return by Reference

  1. #include <iostream>
  2. using namespace std;
  3. // Global variable
  4. int num;
  5. // Function declaration
  6. int& test();
  7. int main()
  8. {
  9. test() = 5;
  10. cout << num;
  11. return 0;
  12. }
  13. int& test()
  14. {
  15. return num;
  16. }
Output
5
In program above, the return type of function test() is int&. Hence, this function returns a reference of the variable num.
The return statement is return num;. Unlike return by value, this statement doesn't return value of num, instead it returns the variable itself (address).
So, when the variable is returned, it can be assigned a value as done in test() = 5;
This stores 5 to the variable num, which is displayed onto the screen.

Important Things to Remember When Returning by Reference.

  • Ordinary function returns value but this function doesn't. Hence, you cannot return a constant from the function.
    int& test() {
        return 2;
    }
  • You cannot return a local variable from this function.
    int& test()
    {
        int n = 2; 
        return n; 
    }

Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website