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++;
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++;
The former is undefined behaviour, since it involves two unsequenced writes to x
. Undefined behaviour means anything goes.
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.
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.