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

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

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

      

Got the answer 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?

+2


source to share


4 answers


"Undefined" means that the standard does not specify what should happen in this situation, so whatever your compiler does is by definition correct. If it always prints 01

, that's fine. If it prints a different number every time it runs, that will be fine too. If it makes the monkeys fly out of your nose (as shown ) that will be fine too.

You might not think so, but the compiler scripting is disabled if this happens.



[Edit: It was stated in the comments that the canonical reference is "nasal demons" and not "nasal monkeys". I apologize for any unintended confusion. Any alleged confusion that I'm proud of and don't apologize for. :-)]

+8


source


You are asking:

why does it even if I compile it 25 times it still prints 01



and the answer is that compilers are mostly (but not entirely) deterministic - given the same input, they will produce the same output. in terms of machine code. and that machine code is also deterministic and therefore always outputs "01". Another C ++ compiler, albeit in the same deterministic way, can generate machine code that produces "10" every time.

+6


source


Because always typing 01

is one of the behaviors your program can have.

+5


source


cout<<c++<<c; 

      

We break it down into 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 and C must be before D. Within these limits, they can be in any order. You can expect them to be executed as ABCD, but they can fairly be executed as ACDB. Or even CADB. In fact, it would be legal to execute them as A- (B & C) -D, with B and C running simulatively on separate processors (which would cause a memory access error, so this is undefined and not just implementation-defined)

+1


source







All Articles