Return by Reference
- A C++ program can be made easier to read and maintain by using references rather than pointers.
- A C++ function can return a reference in a similar way as it returns a pointer.
- When a function returns a reference, it returns an implicit pointer to its return value.
- This way, a function can be used on the left side of an assignment statement. For example, consider this simple program:
Example:
#include <iostream>
int n;
int& test();
int main() {
test() = 5;
cout<<n;
return 0;
}
int& test() {
return n;
}
Output:
5
- In program above, the return type of function
test()
is int&
. Hence this function returns by reference. The return statement is return n;
but unlike return by value. This statement doesn't return value of n, instead it returns variable n itself.
- Then the variable n is assigned to the left side of code
test() = 5;
and value ofn is displayed.
Ask Question