x&&y||z 是如何计算的?
鉴于
int x=1,y=2,z;
您能解释一下为什么结果:
x && y || z
是 1 吗?
x && y = 1
x && y || z = 1
Given
int x=1,y=2,z;
Could you explain why the result for:
x && y || z
is 1?
x && y = 1
x && y || z = 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
相当于
如果
x=1
和y=2
那么
x&&y
就是1 && 2
这是true && true
即true
。始终为
true
。z
甚至没有被评估is equivalent to
if
x=1
andy=2
then
x&&y
is1 && 2
which istrue && true
which istrue
.is always
true
.z
isn't even evaluatedx && y || z
=> <代码>(x && y) || z => <代码>1 || z => <代码>1x && y || z
=>(x && y) || z
=>1 || z
=>1
未初始化的 int 指的是保存在内存中的数据,它被放置在堆栈上......并且它很少是
0x00000000
,即使是,true ||假=真
。Uninitialized int refers to data that was saved in memory, where it is placed on stack... and it rarely is
0x00000000
, and even if it was,true || false = true
.&&
运算符的优先级高于||
运算符。例如,请参阅此运算符优先级表,第 13 和 14 号。您的示例的计算结果为 <代码>(x && y) || z 。由于短路规则,
z
永远不会被计算,因为x && 的结果是: y
已经是true
。The
&&
operator has higher precedence than the||
operator. See, e.g., this operators precedence table, numbers 13 and 14.Your example evaluates as
(x && y) || z
. Thanks to the short circuiting rule,z
is never evaluated because the result ofx && y
is alreadytrue
.你可以想到
x && y || z
相当于:由于
x
和y
都固定为非零值,因此始终会命中第一个 return 语句。在 IA32 上,没有优化
x && y || z
变为:并且
func
变为:启用优化后,
func()
看起来更像表达式(返回值仅从一个位置加载,尽管它是被 x86-isms 掩盖了),但是表达式x && y || z
基本上消失了,因为编译器能够在编译时推断出它的值。You can think of
x && y || z
as equivalent to:Since both
x
andy
are fixed to be non-zero values the first return statement is always hit.On IA32, without optimisation
x && y || z
becomes:And
func
becomes:With optimizations enabled
func()
looks even more like the expression (the return value only gets loaded from one place, although it's obscured by x86-isms), but the expressionx && y || z
basically disappears since the compiler is able to deduce its value at compile time.因为
x && y
的计算结果为(x != 0) && (y != 0)
,相当于1 && 1
结果 1。并且1 ||无论 y 值是什么,0
都是 1。Because
x && y
is evaluated as(x != 0) && (y != 0)
, which is equivalent with1 && 1
resulting 1. And1 || 0
is 1, no matter what y value is.&& 运算符的优先级高于 || 运算符
The && operator has higher precedence than the || operator
这里有两个组成部分:
如果它可以帮助您记住,就数学运算符而言,||可以用加号“+”替换,加号“+”由 2 个条组成,如 &&可以用“.”代替。并且乘法优先于“+”:-)
在 C++ 和 C 中,当计算布尔表达式并且可以从某个项逻辑上推断出结果时,不会计算以下项:
假&& (expr2) 为 false 并且 expr2 不会被求值。
真实 || (expr3) 为 true 并且 expr3 不会被求值。
我希望这有帮助 =)
There are 2 components here:
If it helps you remember, in terms of mathematical operators, || can be replaced with the plus sign "+", which consists of 2 bars and as && can be replaced with a "." and has the multiplication's precedence over the "+" :-)
In C++ and C, when a boolean expression is being evaluated and the result can logically be inferred from a certain term, the following terms do not get evaluated:
false && (expr2) is false AND expr2 does not get evaluated.
true || (expr3) is true AND expr3 does not get evaluated.
I hope this helps =)