Could someone explain me the output of this segment of c++ code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Could someone explain me the output of this segment of c++ code?

int j=5; cout<<++j<<j++<<j; // 757 How? cout<<endl; j=5; cout<<++j; // 6 Then why cout <<j++; // 6 not here cout <<j; // 7 (757)?

22nd Feb 2018, 5:10 AM
Abhimanyu Gupta
Abhimanyu Gupta - avatar
1 Answer
+ 3
To add to Immortal's answer, undefined behavior actually isn't just compiler dependant, it may result in literally any outcome. On the other hand, unspecified behavior is compiler dependant, but not enforced by the standard. In this case, the expression "cout << ++j << j++ << j;" has undefined behavior in pre C++17, and unspecified in C++17. The reason behind this kind of mistake is a common misconception that C++ evaluates lines of code from left to right, one operator at a time. This isn't true. You can read more on this topic here: http://en.cppreference.com/w/cpp/language/eval_order An here's a link to previous similar question, that contains some links to previous questions, and so on: https://www.sololearn.com/Discuss/1077016/?ref=app
22nd Feb 2018, 9:49 AM
deFault