使用赋值作为条件表达式?
考虑一下:
if (a=5) {
/* do something */
}
任务作为条件如何发挥作用?
它是基于左值的非零值吗?
Consider:
if (a=5) {
/* do something */
}
How does the assignment work as a condition?
Is it based on non-zero value of l-value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C++ — ISO/IEC 14882:2003(E)
表达式
a = 5
的结果是5
。发生到
bool
的转换。5
转换为布尔值true
。true
被视为if
语句成功。C — ISO/IEC 9899:1999(E)
表达式
a = 5
的结果是5
。5
被视为if
语句成功。像这样的一般
代码几乎总是一个错误;作者的意图很可能是
if (a == 5) {}
。然而,有时它是故意的。你可能会看到这样的代码:C++ — ISO/IEC 14882:2003(E)
The result of the expression
a = 5
is5
.A conversion to
bool
takes place.5
converts to booleantrue
.true
is treated as anif
statement success.C — ISO/IEC 9899:1999(E)
The result of the expression
a = 5
is5
.5
is treated as anif
statement success.General
Code like this is almost always a mistake; the author likely intended
if (a == 5) {}
. However, sometimes it is deliberate. You may see code like this:每个非零值都将被视为true。
所以有些人会建议你这样写,
以避免你犯==由=的错误。
Every non-zero value will be considered as true.
So some people will suggest you write
to avoid that you make mistake == by =.
if(a=x)
相当于if(x)
,此外还相当于用x
指定的a
。因此,如果表达式 x 的计算结果为非零值,则 if(x) 就变成了 if(true)。否则,它变成if(false)
。在您的情况下,由于
x = 5
,这意味着f(a=5)
除了之外还相当于
分配有if(true)
>a5
。if(a=x)
is equivalent toif(x)
in addition toa
assigned withx
. So if the expressionx
evaluates to a non-zero value, thenif(x)
simply becomesif(true)
. Otherwise, it becomesif(false)
.In your case, since
x = 5
, that meansf(a=5)
is equivalent toif(true)
in addition toa
assigned with5
.是的,它基于分配给 a 的零/非零值。对于某些人(包括我自己)来说,在代码中使用带有副作用的表达式也被认为是不好的做法,因此提到的代码片段最好写成类似
Yes, it is based on the zero/non-zero value which a is assigned. To some people (myself included) it is also considered bad practice to have expressions with side-effects in your code, so the mentioned code fragment would preferably be written as something like
在更现代的用法中,您有时可能会看到此模式用于处理可选的:
In more modern usage, you may sometimes see this pattern used to handle
optional
s: