Search code examples
c++referencelvaluervalue

Confusing L-Value and R-Values parentheses


In this example here at the bottom, there are exemplary l-values defined:

  // lvalues:
  int& foo();
  foo() = 42; // ok, foo() is an lvalue
  int* p1 = &foo(); // ok, foo() is an lvalue

I am not shure what foo() is here? At first sight it looks like a function/method?

Is int& foo() the same as int& foo; ?

But on the other hand, my compiler says

Error: 'foo' declared as reference but not initialized int & foo;

Same with the rvalues foobar():

  // rvalues:
  int foobar();
  int j = 0;
  j = foobar(); // ok, foobar() is an rvalue
  int* p2 = &foobar(); // error, cannot take the address of an rvalue

Solution

  • Yes, it is "a function/method", returning a reference to an int. Or, more precisely, this is a declaration of such a function, not definition: it says that such function exists, but does not provide the actual code (because the code is not relevant for the example). Compare how you define functions in header files.

    A possible example of code for a similar function:

    int a, b;
    int& foo(bool which) {
        if (which) return a;
        else return b;
    } 
    
    ...
    foo(true) = 10; // works as a = 10;