In this article, you’ll learn how to return a value by reference in a function and use it proficiently in your program.
In C++ Programming, not exclusively would you be able to pass values by reference to a function yet you can likewise return a value by reference.
To understand this feature, you should have the knowledge of:
Example: Return 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
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 to return num; In contrast, to return by esteem, this announcement doesn’t restore estimation of num, rather it restores the variable itself (address).
So, when the variable is returned, it tends to be accessed a value as done in the test() = 5;
This stores 5 to the variable num, which is shown 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;
}
Please feel free to give your comment if you face any difficulty here.
