Friday 24 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...