I understand that the expression
i = v[i++]
causes undefined behavior pre-C++17, since we are not sure which action takes place first: the result of i++
being put back to i
, or the value of v[i]
being assigned to i
. But things seem to have changed in C++17.
From N4659 expr.ass
The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.
It seems to me that in C++17, both value computation and side effect of v[i++] is sequenced before assignment operation(=), which makes i = v[i++]
legal, with things taking place in the following order:
- value of
v[i]
is retrieved - side effect of
i++
is enforced,i
is incremented by 1 - the value of
v[i]
retrieved in step 1 is assigned toi
Am I correct?