tags:

views:

91

answers:

1
int a=5;
printf("%d %d %d\n",a++,a++,++a);

Output on Gcc : 7 6 8

Can someone please explain the answer. I apologize if this question has been repeated but i wasn't able to find it.

Thanks!!

+14  A: 

The behaviour is undefined because there are no sequence points between the increment operators.

Explaining why the code does what it does is a pointless exercise. You should not write code that has undefined behaviour, even if it appears to work for you.

To address the point raised in the comments: It is true that the comma operator acts as a sequence point, however the comma here is not a comma operator. From Wikipedia:

The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator.

Mark Byers
Is it because we have multiple increment operations in a single statement? Also doesnt ',' opeartor mantain proper execution in this case.
The Stig
@The Stig: First, it's because the code modifies `a` more than once between sequence points. Second, the comma operator does indeed have a sequence point, but the comma in function calls isn't the comma operator. Confusing, but true.
David Thornley
@David Thornley: Yep. I've added this into my answer. Thanks.
Mark Byers
My main confusion is with the "," as a sequence point.So in a code something like func(foo(),bar()) the "," comma operator is NOT a sequence point but in something like if(foo(),bar()) the comma acts as a sequence point
The Stig
@The Stig: That is correct, except to be pedantic: in your first example the comma is not a "comma operator" it is just a comma token.
Mark Byers
Thanks Mark and David...Confusion cleared !!
The Stig
The rule is simple: order of evaluation of function arguments is not defined. So be prepared for any order. Period.
Piotr Kalinowski
@Piotr: To be pedantic, the order of evaluation of function arguments is unspecified, and can be interleaved or even simultaneous. "Unspecified" means the compiler has to do something reasonable, but may vary in some details, and whatever behavior there is need not be either consistent nor documented. There are some rules on function calls as arguments, in that IIRC they cannot be interleaved with any other argument calculation.
David Thornley
How is "unspecified" different from "not defined" ? :)
Piotr Kalinowski