Why is "++i++" invalid while (++i)++ is valid?
i
and ++i
are both lvalues, but i++
is an rvalue.
++(i++)
cannot be valid, as the prefix ++
is being applied to i++
, which is an rvalue. But (++i)++
is fine because ++i
is an lvalue.
Note that in C, the situation is different; i++
and ++i
are both rvalues. (This is an example of why people should stop assuming that C and C++ have the same rules. People insert these assumptions into their questions, which must then be refuted.)
so the code is parsed as int b = ++(i++); and i is an rvalue.
No. i
is not an rvalue. i
is an lvalue. i++
is an rvalue (prvalue to be specific).
This declaration
int b = ++i++;
is equivalent to
int b = ++( i++ );
The postfix increment operator returns the value of the operand before increment.
From the C++ 17 Standard (8.2.6 Increment and decrement)
1 The value of a postfix ++ expression is the value of its operand...The result is a prvalue.
While the unary increment operator returns lvalue after its increment. So this declaration
int b = (++i)++;
is valid. You could for example write
int b = (++++++++i)++;
From the C++ 17 Standard (8.3.2 Increment and decrement)
1 The operand of prefix ++ is modified by adding 1. The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type other than cv bool, or a pointer to a completely-defined object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field....
Pay attention that in C the both operators return a value instead of lvalue. So in C this declaration
int b = (++i)++;
is invalid.