Why does “int x = 5; printf(”%d %d %d“, x==5, x=10, x==5);” in C print “0 10 0”? [duplicate]

大兔子大兔子 提交于 2019-12-10 17:46:19

问题


I've been studying C for about a year now, and I came across this above when I was just playing around. I first thought maybe it's a case of assignment precedence (i.e. x=10 happens first), but then I tried

printf("%d %d %d", x==5, x=10, x<6);

and it outputs 0 10 1. Could someone please explain to me why/what is going, as this seems extremely baffling to me and I'm starting to think it's undefined behavior perhaps?


回答1:


This is indeed undefined behavior. Arguments to functions are evaluated in an unspecified order, so doing anything that relies on that order becomes UB.

It looks like your compiler goes right-to-left (at least in this instance). That's a reasonable way to do it. But since it's UB, don't count on it always doing that.



来源:https://stackoverflow.com/questions/56086241/why-does-int-x-5-printfd-d-d-x-5-x-10-x-5-in-c-print-0-10-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!