Is “++l *= m” undefined behaviour?

后端 未结 2 1803
暗喜
暗喜 2021-01-17 09:42

I have started studying about C++0x. I came across the follow expression somewhere:

int l = 1, m=2;
++l *= m;

I have no idea whether the se

2条回答
  •  一整个雨季
    2021-01-17 10:06

    In the code above, prefix ++ has precedence over *=, and so gets executed first. The result is that l equals 4.

    UPDATE: It is indeed undefined behavior. My assumption that precedence ruled was false.

    The reason is that l is both an lvalue and rvalue in *=, and also in ++. These two operations are not sequenced. Hence l is written (and read) twice "without a sequence point" (old standard wording), and behavior is undefined.

    As a sidenote, I presume your question stems from changes regarding sequence points in C++0x. C++0x has changed wording regarding "sequence points" to "sequenced before", to make the standard clearer. To my knowledge, this does not change the behavior of C++.

    UPDATE 2: It turns out there actually is a well defined sequencing as per sections 5.17(1), 5.17(7) and 5.3.2(1) of the N3126 draft for C++0x. @Johannes Schaub's answer is correct, and documents the sequencing of the statement. Credit should of course go to his answer.

提交回复
热议问题