What does "int& foo()" mean in C++?

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

I tried it in g++, but the compiler says "undefined reference to foo()". If I add

int foo()
{
  return 2;
}

int main()
{
  int& foo();
  foo() = 42;
}

It compiles fine, but running it gives a segmentation fault. Just the line

int& foo();

by itself both compiles and runs without any problems.

What does this code mean? How can you assign a value to a function call, and why is it not an rvalue?


Solution 1:

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
}

Solution 2:

All the other answers declare a static inside the function. I think that might confuse you, so take a look at this:

int& highest(int  & i, int  & j)
{
    if (i > j)
    {
        return i;
    }
    return j;
}

int main()
{
    int a{ 3};
    int b{ 4 };
    highest(a, b) = 11;
    return 0;
}

Because highest() returns a reference, you can assign a value to it. When this runs, b will be changed to 11. If you changed the initialization so that a was, say, 8, then a would be changed to 11. This is some code that might actually serve a purpose, unlike the other examples.