开发者

Is this example causing an undefined behaviour? [duplicate]

开发者 https://www.devze.com 2023-03-08 07:02 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Undefined Behavior and Sequence Points
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Undefined Behavior and Sequence Points

The variable i is changed twice, but is the next example going to cause an undefined behaviour?

#include <iostream>
int main()
{
    int i开发者_JAVA技巧 = 5;
    std::cout << "before i=" << i << std::endl;
    ++ i %= 4;
    std::cout << "after i=" << i << std::endl;
}

The output I get is :

before i=5
after i=2


Yes, it's undefined. There is no sequence point on assignment, % or ++ And you cannot change a variable more than once within a sequence point.

A compiler could evaluate this as:

++i;
i = i % 4;

or

i = i % 4;
++i;

(or something else)

0

精彩评论

暂无评论...
验证码 换一张
取 消