Tuesday, 6 September 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...