Search code examples
c++implicit-conversionlvaluervaluelvalue-to-rvalue

Will an lvalue to rvalue conversion happen?


C++ Standard (4/5) the lvalue-to-rvalue conversion is not done on the operand of the unary & operator.

For example:

int x;
int *p = &x;

In the above case, are p are &x both lvalues? or What would be an appropriate example?

Edit:

What about this?

int &r = x;

I'm sure there will be no conversion in this statement, but i'm confused how does & operator involve in this?


Solution

  • The quote says that the conversion is not applied on the operand of unary & (in this case, x). So the operand of & is an lvalue.

    This is different from, say, the unary + operator. If you write +x, then lvalue-to-rvalue conversion is applied to the sub-expression x (with undefined behavior in this case, since x hasn't been initialized).

    Informally, "lvalue-to-rvalue conversion" means "reading the value".

    The quote doesn't say anything about the result of &, which in fact is an rvalue. In int *p = &x;:

    • x is an lvalue, referring to the variable of that name,
    • &x is an rvalue, it's part of the initializer (specifically, an assignment-expression),
    • p is neither an rvalue nor an lvalue, because it is not a (sub-)expression. It's the name of the variable being defined. In the C++ declarator grammar it's the declarator-id (8/4 in the C++03 standard).

    int &r = x; doesn't use the & address-of operator at all. The & character in the declarator is just the syntax meaning that r is a reference-to-int, it's not taking the address of r. In the C++ declarator grammar, it's actually called the ptr-operator.