1
#include <iostream>

using namespace std;

int main(){

int j=0;

cout << ++j << j++ << j;

return 0;
}

To my knowledge, the output of the code must be 1 1 2 but the output of the code is 2 0 2, and this answer varies from compiler to compiler I am using the latest version of gcc. But when I use turbo c compiler the output is different.

So please explain the background working of the code.

Gs niteesh
  • 19
  • 3
  • 3
    This program exhibits undefined behavior, and therefore can produce any outcome whatsoever. E.g. see http://stackoverflow.com/questions/24194076/in-c11-does-i-i-1-exhibit-undefined-behavior – Igor Tandetnik Mar 22 '17 at 03:58
  • 1
    << is an overloaded operator., so ++j, j++, j end up being function arguments. The order of evaluation of function arguments is undefined. – Avi Berger Mar 22 '17 at 04:03
  • Pretty much identical to http://stackoverflow.com/questions/42891791/postfix-and-prefix-operator-giving-unexpected-answer-in-cout-statement – Raymond Chen Mar 22 '17 at 05:57
  • 1
    Possible duplicate of [Undefined behavior and sequence points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – Raymond Chen Mar 22 '17 at 05:57
  • 1
    You can't modify `j` multiple times in the same statement like that - it's UB. Do this instead: `cout << ++j; cout << j++; cout << j;`. – Jesper Juhl Mar 22 '17 at 06:00

1 Answers1

1
cout << ++j << j++ << j;

Order of execution for '++j' and 'j++' here is not specified at all (both of them are function operator << () arguments). Compilers treat this as undefined behavior. On this line, anything could happen and no results are guaranteed. You can read about it here.

CaptainTrunky
  • 1,562
  • 2
  • 15
  • 23