While reading this explanation on lvalues and rvalues, these lines of code stuck out to me:
int& foo();
foo() = 42; // OK, foo() is an lvalue
The explanation is assuming that there is some reasonable implementation for foo
which returns an lvalue reference to a valid int
.
Such an implementation might be:
int a = 2; //global variable, lives until program termination
int& foo() {
return a;
}
Now, since foo
returns an lvalue reference, we can assign something to the return value, like so:
foo() = 42;
This will update the global a
with the value 42
, which we can check by accessing the variable directly or calling foo
again:
int main() {
foo() = 42;
std::cout << a; //prints 42
std::cout << foo(); //also prints 42
}
int& foo();
Declares a function named foo that returns a reference to an int
. What that examples fails to do is give you a definition of that function that you could compile. If we use
int & foo()
{
static int bar = 0;
return bar;
}
Now we have a function that returns a reference to bar
. since bar is static
it will live on after the call to the function so returning a reference to it is safe. Now if we do
foo() = 42;
What happens is we assign 42 to bar
since we assign to the reference and the reference is just an alias for bar
. If we call the function again like
std::cout << foo();
It would print 42 since we set bar
to that above.
The function you have, foo(), is a function that returns a reference to an integer.
So let's say originally foo returned 5, and later on, in your main function, you say foo() = 10;
, then prints out foo, it will print 10 instead of 5.
I hope that makes sense :)
I'm new to programming as well. It's interesting to see questions like this that makes you think! :)