-4

So in c++ why are these 2 outputs different?

int x;
for(int x=2;x<5;x++);
cout<<x<< x++ << ++x << x <<endl;

this out outputs 7677

cout<<x<<endl;
cout<<x++<<endl;
cout<<++x<<endl;
cout<<x<<endl;

this out outputs 5577

so why are they different?

what i guessed is the first one computes the entire line at the same time that's why it outputs 7 but then why would ++x still output 6? is there some kind of priority here or what is going on?

Justaname
  • 21
  • 5
  • First, your `x` is not initialized in the first example. The `x` in the loop is not the same as the one declared globally. – PaulMcKenzie May 19 '18 at 00:49
  • Because only one of them is well-defined, while the other one is undefined behavior (no sequence points, uninitialized `x` because of semicolon after the loop). – Sergey Kalinichenko May 19 '18 at 00:50
  • https://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior-in-c applies to C++ here. – Ry- May 19 '18 at 00:52
  • The first has undefined behaviour, which means any results are permitted, since the two modifications of `x` are unsequenced. Therefore, any behaviour is permitted, whether it makes sense to you or not. The second has well defined behaviour. – Peter May 19 '18 at 00:53
  • 1
    How could this code compile, since you have `i` in the `for` loop, and not `x`? Make sure that if you're going to show output for a block of code, copy and paste the *exact* code you're running -- don't hastily type in code into the edit window. – PaulMcKenzie May 19 '18 at 00:56
  • 1
    output will be well defined in c++17. – Jarod42 May 19 '18 at 01:03
  • 1
    What is `i` in `for(int x=2;i<5;x++);`??? What is the purpose of this cycle with empty body? – AnT stands with Russia May 19 '18 at 01:19
  • Given that this question was asked at all, it is a pretty fair bet the OP is not using a C++17 compiler so the relevant standard predates C++17 - in which case the behaviour is undefined. – Peter May 19 '18 at 01:25

1 Answers1

0

It shouldn't be different in C++17, but not before it.

In a shift operator expression E1<<E2 and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2 (since C++17)

If you use a C++ standard before C++17, then the behavior is undefined, so the complier can do any work you don't want.

If you want to learn more about in which context can a evaluation expression lead an Undefined Behavior, see this:

https://en.cppreference.com/w/cpp/language/eval_order

con ko
  • 1,368
  • 5
  • 18