In which versions of the C++ standard does “(i+=10)+=10” have undefined behaviour?

后端 未结 3 1291
故里飘歌
故里飘歌 2020-12-03 02:30

In C++, does the following have undefined behaviour:

int i = 0;
(i+=10)+=10;

There was some debate about this in the comments to my answer

3条回答
  •  -上瘾入骨i
    2020-12-03 03:27

    In C++11 the expression is well defined and will result in i == 20.

    From [expr.ass]/1:

    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 means that the assignment i+=1 is sequenced before the value computation of the left hand side of (i+=10)+=10, which is in turn sequenced before the final assignment to i.


    In C++03 the expression has undefined behavior, because it causes i to be modified twice with no intervening sequence point.

提交回复
热议问题