Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 538
user1086635 Avatar asked May 05 '26 23:05

user1086635


2 Answers

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.

like image 109
Steve Jessop Avatar answered May 08 '26 14:05

Steve Jessop


Think of lvalue as storage place and of rvalue as the value to store there. Therefore *p is lvalue and &x is rvalue. However, & requires an lvalue as operand (x) but the result is a rvalue, but this does not change x itself.

like image 39
Sebastian Dressler Avatar answered May 08 '26 14:05

Sebastian Dressler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!