为什么 "int x = 5;printf("%d %d %d", x==5, x=10, x==5);";在 C 中打印“0 10 0"? [英] Why does "int x = 5; printf("%d %d %d", x==5, x=10, x==5);" in C print "0 10 0"?

查看:74
本文介绍了为什么 "int x = 5;printf("%d %d %d", x==5, x=10, x==5);";在 C 中打印“0 10 0"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学习 C 大约一年了,我在玩的时候遇到了上面的这个.我首先想到可能是分配优先的情况(即 x=10 先发生),但后来我尝试了

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);

它输出<代码>0 10 1.有人可以向我解释为什么/发生了什么,因为这对我来说似乎非常令人困惑,我开始认为这可能是未定义的行为吗?

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?

推荐答案

这确实是未定义的行为.函数的参数以未指定的顺序计算,因此执行任何依赖于该顺序的操作都会成为 UB.

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

看起来你的编译器是从右到左的(至少在这种情况下).这是一个合理的方法.但既然是 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.

这篇关于为什么 &quot;int x = 5;printf("%d %d %d", x==5, x=10, x==5);";在 C 中打印“0 10 0"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆