The result of int c=0; cout<<c++<<c;

后端 未结 5 1901
无人及你
无人及你 2020-12-06 19:29

I think it should be 01 but someone says its \"undefined\", any reason for that?

5条回答
  •  再見小時候
    2020-12-06 20:08

    It is undefined behavior if you modify a value and then read it (or try to modify it again) without an intervening sequence point. The concept of a sequence point in C++ is a bit technical (you can read a little about it here), but the bottom line is that stream insertion (<<) is not a sequence point.

    The reason why this is undefined behavior is because, in the absence of a sequence point, the compiler is allowed to re-order operations in any way it sees fit. That is, it is permitted to retrieve the value of c (and hold onto it for the second insertion) and then afterwords execute c++ to get the value for the first insertion. So you can't be sure whether the increment will occur before or after the value of c for the second insertion is determined.

提交回复
热议问题