Jan 29, 2009 at 8:48am UTC
void main()
{
int a=10;
cout<<++a<<a;
}
the above code gives the output as 20, 10. please explain
Jan 29, 2009 at 9:01am UTC
Are you sure it outputs 20, 10?
It looks like it would output 1111.
Jan 29, 2009 at 9:10am UTC
strictly speaking the above code is illegal
there is no sequence point in between to determine whether '++a' or 'a' should be evaluated first therefore the return value and what cout prints is undefined.
Last edited on Jan 29, 2009 at 9:13am UTC
Jan 29, 2009 at 10:29am UTC
I haven't given this much thought before (and I may be wrong) but isn't
std::cout << ++a << a;
just a tidy way of writing
std::cout.operator <<(++a).operator <<(a);
and therfore it will have sequence points because you are calling the operator functions?
Jan 29, 2009 at 8:44pm UTC
Yes, but it is still up to the compiler to decide when to post increment.
The code is not illegal; it's output is just undefined.
Jan 29, 2009 at 8:49pm UTC
I don't see how it would be undefined?
Execution order would be evaluated left to write, and the pre-increment before function call. So the output is well defined.
The order would be
++a
cout << a;
cout << a;
if it was cout << a << ++a;
then it'd be
cout << a;
++a;
cout << a;
What's undefined about that?
Jan 29, 2009 at 10:24pm UTC
Not on all the operators the operands are for sure evaluated from left to right
eg: on VC++ cout << ++a << a;
and cout << a << ++a;
display the same output but on MingW don't
Last edited on Jan 29, 2009 at 10:33pm UTC
Jan 29, 2009 at 10:43pm UTC
hmmm. Is there anything in the standard relating to that?
It seems as though VC++ is doing some instruction re-ordering thereby giving undefined results. In this case, it seems very un-intuitive.
What about doing cout << (++a) << (a);
etc?
Last edited on Jan 29, 2009 at 10:46pm UTC
Jan 29, 2009 at 10:55pm UTC
It was kind of making sense until I tried
std::cout << a << a-- << std::endl;
Jan 29, 2009 at 11:01pm UTC
jsmith is right. The moment at which the increment is done is undefined:
VC++:
b=++a + ++a + a++ + a++;
is the same as
++a;
++a;
b=a+a+a+a;
++a;
++a;
GCC:
b=++a + ++a + a++ + a++;
is the same as
++a;
b=a;
++a;
b+=a+a;
++a;
b+=a;
++a;
EDIT:
Grey Wolf: I get "10 10" for a=10.
Last edited on Jan 29, 2009 at 11:07pm UTC
Jan 29, 2009 at 11:07pm UTC
VC gives 9 10 for a=10.
It's late (here), I'm off to sleep...
Last edited on Jan 29, 2009 at 11:09pm UTC
Jan 29, 2009 at 11:12pm UTC
Okay, I was wrong.
Both VC++ and GCC (or at least MinGW) seem to be doing
++a;
++a;
b=a+a+a+a;
++a;
++a;
Well, my point stands. There some compiler that does
++a;
b=a;
++a;
b+=a+a;
++a;
b+=a;
++a;
Jan 30, 2009 at 12:11am UTC
behavior undefined -> illegal in my book.