问题描述
据我所知逻辑运算符&放大器;&安培;
具有较高的precedence比 ||
。在运行code:
的#include<&stdio.h中GT;诠释的main()
{
INT I = 1,J = 1,K = 1; 的printf(%d个\\ n,++我|| ++ J&安培;&安培; ++ K);
的printf(%D%D,I,J,K); 返回0;
}
是给输出:
1
2 1 1
这是可能的,只有当 ++我|| ++ J&安培;&安培; ++氏/ code>评估是这样的:
(++ I)|| (++ J&安培;&安培; ++ K)
但是,根据操作者precedence规则应当评估为:
(++我|| ++ j)条和放大器;&安培; (++ K)
,因此输出应该是:
1
2 1 2
这有什么问题呢?
注意:按照我的理解,我认为评估为更高的precedence的操作如下(如果是左关联的):结果
1.评估其左恩pression结果
2.然后评估其右侧前pression(如果需要)结果
难道我错了吗?
解决方案 您说的:
The first grouping is correct because the precedence of &&
is higher than the precedence of ||
. Then the expression as a whole evaluates the LHS of the ||
, with the side-effect of incrementing i
, which evaluates to true. That means that the RHS of the ||
(the &&
expression) is not evaluated at all because it is not needed to determine the truth of the overall expression.
So, the compiler is correct; you misunderstood precedence in some way.
You don't understand precedence, it seems, or you don't understand the interaction of precedence with order of evaluation. The first grouping gives higher precedence to &&
.
If you have a + b * c
, where *
has a higher precedence than +
, then it is evaluated as a + (b * c)
, is it not? Change +
to ||
and *
to &&
and the expressions are isomorphic and the interpretation is similar.
The big difference between the arithmetic expression and the logical expression is that the operands of the logical expression have to be evaluated left-to-right but the operands of the arithmetic expression do not; the compiler could evaluate b * c
before evaluating a
(but must evaluate b * c
before doing the addition). By contrast, in the logical expression (a || b && c
), the compiler must evaluate a
before evaluating b && c
, and when a
turns out to be true, it must not evaluate either b
or c
, let alone b && c
.
这篇关于的和放precedence;&安培;在||的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!