1

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:

  1. value of v[i] is retrieved
  2. side effect of i++ is enforced, i is incremented by 1
  3. the value of v[i] retrieved in step 1 is assigned to i

Am I correct?

megamonium
  • 463
  • 3
  • 7
  • 1 and 2 can be swapped – Caleth Apr 16 '20 at 08:09
  • 3
    [What made i = i++ + 1; legal in C++17?](https://stackoverflow.com/q/47702220/4389800) – P.P Apr 16 '20 at 08:12
  • 2
    Legal or not, that code would fail a code review. – john Apr 16 '20 at 08:12
  • @Caleth But why? Suppose i = 1 at the beginning, if things took place as I said, v[1] is retrieved in step 1. If steps 1 and 2 were swapped, then v[2] will be retrieved in step 2. So swapping steps 1 & 2 obviously produces different results? I'm puzzled. – megamonium Apr 16 '20 at 08:12
  • @john Yes, but I'm just using this code as an example to test if my understanding of the new standard is accurate. – megamonium Apr 16 '20 at 08:14
  • @megamonium: 1 and 2 swapped, would *"result"* in `++i, v[i - 1]`; – Jarod42 Apr 16 '20 at 08:14
  • In that example, `i++` results in the *value* `1`, and afterward `i == 2`. The `1` is used to index `v`, it no longer has a relation to `i`. – Caleth Apr 16 '20 at 08:18
  • @john https://en.wikipedia.org/wiki/Security_through_obscurity :P – Timo Apr 16 '20 at 08:26
  • I see. So you are saying that `i` may be incremented before or after the pre-increment value of `i` is used to index into `v`. It is not specified by the standard. Got you. – megamonium Apr 16 '20 at 08:31

0 Answers0