0

Can someone explain why the following two snippets have different output?

int x=0;
cout<<x++<<" "<<x++;

and

int x=0;
cout<<x++<<" ";
cout<<x++;
Jeff
  • 6,643
  • 3
  • 25
  • 35
Ali Haider
  • 33
  • 4
  • It is undefined behavior. http://stackoverflow.com/questions/7874399/how-post-increment-pre-increment-both-are-evaluated-in-function-argument – Pranit Kothari Feb 01 '14 at 07:14

3 Answers3

1

The former is undefined behaviour, since it involves two unsequenced writes to x. Undefined behaviour means anything goes.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
0

Multiple writes on the same object between two sequence points is undefined behavior. Your first code snippet modifies the value of x twice before the next sequence point appears, so it's undefined behavior. Don't write code like this. Exploring the possible outputs of this code on different implementations is also meaningless.

neverhoodboy
  • 1,040
  • 7
  • 13
-2
int x = 0; cout<<x++<<" "<<x++

is similar to,

int x = 0;
cout<<x;
cout<<" ";
x = x+1;
x = x+1;

So at that line you will get printed a 0, while x will be 2 if you run a cout<<x just below that line.

The second statement,

int x=0; cout<<x++<<" "; cout<<x++;

is equivalent to,

int x =0;
cout<<x;
cout<<" ";
x = x+1; //note x gets 1 here
cout<<x; //will print 1 here due previous increment, not the second one
x = x +1;

So in this case you will get printed a 1, but again x will be 2 if you run a cout<<x at the next line.

Abdullah Leghari
  • 2,332
  • 3
  • 24
  • 40