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 of n is displayed.
I don't quite understand the bold sentence.
Shouldn't value of n and variable n be the same?
If it was just the variable, doing test() = 5; would be like 0=5;(I don't believe it would make an error, but probably a warning), and with the reference"&", its like n = 5;.
int n = 5 ; // 'n' is a variable; it denotes an object of type int
int& r = n ; // 'r' is a variable; it denotes a reference to int (an alias for an object of type int)
// in this case, 'r' is an alias for the object of type int denoted by the variable 'n'
When evaluated as an expression, both (n) and (r) yield a value (an lvalue) of type int.
Sorry, I am still confused about returning a reference.
In the case above, the test() function will return a variable &n and this is an alias for n?
Then the alias is assigned with the value 5, meaning that &n = 5.
So, n = 5.
P.S:
I think here is what I am confused about. Let's consider the assignment below: a = 3;
What it does here is assign rvalue of (3) to lvalue of (a). Is that right?
int foo() // return type is not a reference
{
int temp = 5 ;
return temp ;
}
The expression foo() is a prvalue (pure rvalue) of type int.
The prvalue, in this case is a value not associated with any object.
In other cases, a prvalue (for instance a prvalue of type std::string) may identify a temporary object.
With this function:
1 2 3 4 5 6
int& bar() // return type is (lvalue) reference to int
{
staticint i = 5 ; // static storage duration
// life-time of the object does not end when the function returns
return i ;
}
The expression bar() is an lvalue of type int
The lvalue identifies a non-temporary object of type int