Double assignment of the same variable in one expression in C++11

前端 未结 3 1443
慢半拍i
慢半拍i 2021-02-13 20:14

The C++11 standard (5.17, expr.ass) states that

In all cases, the assignment is sequenced after the value computation of the right and left operands, a

3条回答
  •  温柔的废话
    2021-02-13 20:35

    After doing a little research, I am convinced your codes behaviour is well defined in C++11.

    $1.9/15 states:

    The value computations of the operands of an operator are sequenced before the value computation of the result of the operator.

    $5.17/1 states:

    The assignment operator (=) and the compound assignment operators all group right-to-left.

    If I understand correctly, in your example

    a = (a+=1) = 10;
    

    this implies that the value computations of (a+=1) and 10 have to be made before the value computation of (a+=1) = 10 and the value computation of this expression has to be finished before a = (a+=1) = 10; is evaluated.

    $5.17/1 states:

    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.

    This implies that the assignment must happen before the value computation, and therefore, due to transitivity, the evaluation of (a+=1) = 10 can only begin after the assignment a+=1 (Because its value may only be computed after the side effect).

    The same is true for the second and third assignment.

    See also this excellent answer, which explains the sequenced-before relation in much more detail and way better than I could.

提交回复
热议问题