Why the output is 2 and 0 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why the output is 2 and 0

Int x=0; Cout<<++x<<" "<<x++<<endl;

6th Jan 2020, 1:18 PM
محمود شاكر
محمود شاكر - avatar
4 Answers
+ 3
I think the output should be undefined behaviour, because you are changing the same value and using it again between the same two sequence points. If I run it here on Sololearn, I get 1 1 as output. In what situation did you get 2 and 0?
6th Jan 2020, 1:30 PM
HonFu
HonFu - avatar
+ 3
HonFu You are correct. I didn't put every results of the tests 😁 * In Code Playground: C++ code - printf("%d %d\n", ++x, x++); // 2 0 - cout << ++x << " " << x++ << endl; // 1 1 C code - printf("%d %d\n", ++x, x++); // 2 0 * In C4Droid (C code) - printf("%d %d\n", ++x, x++); // 1 1 I hope this gives the OP an idea what a mess this sequence point thing was all about.
6th Jan 2020, 1:55 PM
Ipang
+ 2
That is not a definite answer محمود شاكر . Output of such a code where a variable is accessed and modified in a single point of execution sequence is unpredictable. Output in different compiler will most likely be different also. I tested that line in C4Droid and get 1 1 for output. In Code Playground the result is 2 0, but you will see the sequence point warning. This is something unexplainable, because the result depends on compiler implementation.
6th Jan 2020, 1:37 PM
Ipang
+ 1
Funny. I got 1 1 right here. Maybe not even the same every time in one environment?
6th Jan 2020, 1:38 PM
HonFu
HonFu - avatar