explain outpt

void main()
{
int a=10;
cout<<++a<<a;
}
the above code gives the output as 20, 10. please explain
closed account (z05DSL3A)
Are you sure it outputs 20, 10?
It looks like it would output 1111.
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
closed account (z05DSL3A)
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?
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.
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?
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
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
closed account (z05DSL3A)
It was kind of making sense until I tried
std::cout << a << a-- << std::endl;
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
closed account (z05DSL3A)
VC gives 9 10 for a=10.

It's late (here), I'm off to sleep...
Last edited on
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;
behavior undefined -> illegal in my book.
Topic archived. No new replies allowed.