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

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.


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 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
}