Unknown behavior | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Unknown behavior

#include <iostream> using namespace std; int main() { int x=3; cout<<x++<<"×"<<x<<"x"<<x++; return 0; } expected output 3x4x4 but the output is 5x4x3 i cant understand why I made some search and i find it is related to sequence state but i cant understand how

17th May 2017, 5:37 AM
Moustafa Shahin
Moustafa Shahin - avatar
3 Answers
+ 7
What you're doing is the equivalent of multiple nested function calls to cout.operator<<. Basically, the issue comes from the fact that function parameters can be evaluated in any order the compiler sees fit. The last "x++" might be evaluated first, for example. In general, you run into undefined behavior when you try to modify a variable more than once within the same sequence point. For example, each separate line of code is a sequence point (that may be an oversimplification, but you can usually think of it like that). Edit: Don't listen to @Mason Krei. While it's true that STL streams use a buffer, the buffer does not store references (it uses a simple byte array), and it is not at all the cause of the problem-- the problem is modifying the same variable more than once within the same sequence point. To offer a more thorough explanation, what you have is equivalent to this: operator<<(operator<<(operator<<(operator<<(operator<<(cout, x++),"x"), x), "x"), x++); These calls can be evaluated in any order by the compiler. Either parameter may be evaluated first, and depending on the ordering the compiler selects, you'll get different outputs, since both sides modify "x". You can find more information here: http://en.cppreference.com/w/cpp/language/eval_order
17th May 2017, 7:16 AM
Squidy
Squidy - avatar
+ 1
@Squidy is right and I retract my answer.
17th May 2017, 6:08 PM
Mason Krei
Mason Krei - avatar
0
thank you @Squidy your answer is very helpful for me after a little bit search . I got an enough knowledge about sequence point and changes at the execution. and i should care about the cpp compiler rules to avoid invalid code . and ishould use above 2014 compilers sorry about my english😆
18th May 2017, 8:25 AM
Moustafa Shahin
Moustafa Shahin - avatar