[英]Operators Precedence in C
printf ("%d \n", 2 > !3 && 4 - 1 != 5 || 6 ) ;
Can someone explain to me how this is evaluated?有人可以向我解释这是如何评估的吗? What I am most confused about is the
!
我最困惑的是
!
symbol in front of the 3... how to evaluate 2 > !3
? 3 前面的符号...如何评估
2 > !3
?
. . is the logical not.
是逻辑不。 Meaning it returns 1 for 0 or 0 for any other value.
这意味着它为 0 返回 1 或为任何其他值返回 0。
!0 == 1
!1 == 0
!897489 == 0
So in your example 2 > !3
will be evaluted 2 > 0
which is 1
因此,在您的示例中
2 > !3
将被评估为2 > 0
即1
For your whole expression you will have对于您的整个表情,您将拥有
2 > !3 && 4 - 1 != 5 || 6
2 > 0 && 3 != 5 || 6
1 && 1 || 6 && is higher precedence || but some compiler will warn (gcc)
1 || 6 the 6 will not be evaluated (touched) because of short-circuit evaluation
1
Here is a table of operator precedence .这是运算符优先级表。 From this we can deduce that in your expression
由此我们可以推断出你的表达方式
!
has the highest precedence-
comes next -
接下来是>
comes next >
接下来是!=
comes next !=
接下来&&
comes next &&
接下来||
comes next!
means logical not !0 == 1
, !anythingElse == 0
.表示逻辑不是
!0 == 1
, !anythingElse == 0
。
The expression is evaluated as表达式被评估为
((2 > (!3)) && ((4 - 1) != 5)) || 6
Generally, the order of evaluation of the operands is unspecified, so in the case of通常,操作数的求值顺序是未指定的,因此在
2 > !3
the compiler is free to evaluate !3
before evaluating 2
编译器可以在评估
2
之前自由评估!3
However, for && and ||, the left side is always evaluated first so that short circuiting can be used (with &&
if the left side is false (0), the right side is not evaluated, with ||
if the left side is true (anything but 0), the right side is not evaluated).但是,对于 && 和 ||,总是首先评估左侧,以便可以使用短路(如果左侧为假 (0),则使用
&&
,如果左侧为假 (0),则不评估右侧,使用||
true(除 0 以外的任何值),不评估右侧)。 In the above, the 6
would never be evaluated because the left side of ||
在上面,
6
永远不会被评估,因为||
的左侧is true.是真的。 With
和
6 || ((2 > (!3)) && ((4 - 1) != 5))
6 is true so the right side will never be evaluated. 6 为真,因此永远不会评估右侧。
Its best to use parentheses to have your own order.最好使用括号来有自己的顺序。 Otherwise, operator precedence is explained in the C Operator Precedence Table .
否则,运算符优先级在C 运算符优先级表中进行了说明。
From the above link:从上面的链接:
!3
!3
2 > !3
2 > !3
the.这。 sign convert the value in 0 in binary so 2>!3 means 2>0 and this will be always true and 4-1 equals to 3 not equals to 5||6.
符号将 0 中的值转换为二进制,因此 2>!3 表示 2>0,这将始终为真,并且 4-1 等于 3 不等于 5||6。 5||6 gives you 1 always so the whole command print 1
5||6 总是给你 1 所以整个命令打印 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.