开发者

Expected output for this code [duplicate]

This question already has answers here: 开发者_如何学C Why are these constructs using pre and post-increment undefined behavior? (14 answers) Closed 5 years ago.
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!!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜