Friday, August 24, 2018

c++ - Compiler behavior when evaluating sub-expressions

#include 


int main()
{
int a = 0;
std::cout << a++ << ' ' << ++a << ' ' << a++ << '\n';
}


This code gives me this output 2 3 0 when compiled with C++11 on ideone.




As mentioned here here I know that modifying the value of a variable more than once without an intervening sequence point will cause undefined behavior, but since C++ doesn't evaluate expressions from left to right and computers doesn't behave randomly, I would like to know how does the compiler decide which sub-expression to chose first, second, and third in the above example.



edit: I'm using Microsoft Visual Studio 2013, and the question was asked by a student and I could't explain why do we get those random results.

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...