Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected output for this code [duplicate]

Tags:

c

gcc

increment

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!!

like image 437
The Stig Avatar asked Jul 15 '10 20:07

The Stig


Video Answer


1 Answers

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.

like image 78
Mark Byers Avatar answered Nov 02 '22 19:11

Mark Byers