开发者

Why is this undefined behavior when I always get the same result?

开发者 https://www.devze.com 2022-12-27 03:30 出处:网络
I recently came across a question about sequence points in C++ atthis site, about what this code will output:

I recently came across a question about sequence points in C++ at this site, about what this code will output:

int c=0;
cout << c++ << c;

It was answ开发者_高级运维ered that the output is undefined and << is not a sequence point, but still I want to know why is it undefined when, even if I compile it 25 times, it still always prints 01?


"Undefined" means that the standard doesn't specify what has to happen in that situation, so anything your compiler does is, by definition, right. If it always prints 01, that's fine. If it prints a different number every time you run, that would be fine too. If it causes monkeys to fly out of your nose (as illustrated here), that would be fine as well.

You might not think so, but the compiler writers are off the hook if it happens.

[Edit: It has been pointed out in the comments that the cannonical reference is "nasal demons", not "nasal monkeys". My apologies for any unintended confusion. Any intended confusion I'm proud of and do not apologize for. :-) ]


You ask:

why does it that even if i compile it 25 times it still prints 01

and the answer is because compilers are basically (but not totally) deterministic - given the same input, they will produce the same output. in terms of machine code. and that machine code is also deterministic, and so always outputs "01". Another C++ compiler though might, in a similarly deterministic fashion, produce machine code that produces "10" every time.


Because always printing 01 is one of the behaviors your program is allowed to have.


cout<<c++<<c; 

Let us break this down into its parts:

int c1 = c;        // A
c = c + 1;         // B
int c2 = c;        // C
cout << c1 << c2;  // D

Now, what do we know about the order of these operations? A must be before B, and A & C must be before D. Within those limits, they can be in any order. You may expect them to be executed as A-B-C-D, but they could just as validly be executed as A-C-D-B. Or even C-A-D-B. In fact, it would be legal to execute them as A-(B&C)-D, with B & C executed simulataniously on separate CPUs (which would cause a memory access error, which is why this is undefined and not merely implemention-defined behavior)

0

精彩评论

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