请解释一下precedence与放大器之间的明显冲突;放大器&;和||与前任pression的实际结果 [英] Please explain an apparent conflict between precedence of && and || and the actual result of an expression
问题描述
我不明白以下程序的输出:
I don't understand the output of the following program:
#include<stdio.h>
int main()
{
int i=-3, j=2, k=0, m;
m = ++i || ++j && ++k;
printf("%d %d %d %d\n", i, j, k, m);
return 0;
}
输出为 -2 2 0 1
而不是 -2 3 1 1
,这意味着 ++我
评估(并引起了 ||
运营商短路其右手侧)的前$ p $前pssion ++ J&安培;&安培; ++氏/ code>这似乎矛盾的事实,即
&放大器;&安培;
运营商具有较高的precedence比 | |
。
The output is -2 2 0 1
instead of -2 3 1 1
, implying that ++i
was evaluated (and caused the ||
operator to short-circuit its right hand side) before the expression ++j && ++k
which appears to contradict the fact that the &&
operator has higher precedence than ||
.
会有人解释,为什么?
推荐答案
这位前pression:
The expression:
++i || ++j && ++k
等同于:
(++i) || ((++j) && (++k))
解释:
-
++我
评估 -( - 2)|| ((++ j)条和放大器;及(++ K))
; - 的
||
运营商评估 -(1)
;
++i
is evaluated --(-2) || ((++j) && (++k))
;- The
||
operator is evaluated --(1)
;
由于 1 ||什么
演算值为真,右边的操作数不计算。因此,&放大器;&安培;
precedence此处无关紧要。这种短路在C和C由相关标准保证++(见发生短路的C / C ++?和评估才能授权布尔运算符? )。
Since 1 || anything
evalutes true, the right operand is not evaluated. Thus, the &&
precedence doesn't matter here. This short circuiting is guaranteed in both C and C++ by the relevant standards (see Is short-circuiting boolean operators mandated in C/C++? And evaluation order?).
现在,请尝试使用子前pression,像这样的:
Now, try using a sub-expression, like this:
(++i || ++j) && ++k
这是等同于:
((++i) || (++j)) && (++k)
解释:
-
++我
评估 -(( - 2)||(++ j)条)及和放大器; (++ K)
; -
||
评估 -(1)及和放大器; (++ K)
-
++氏/ code>评估 -
(1)及和放大器; (1)
; - 判断为真;
++i
is evaluated --((-2) || (++j)) && (++k)
;||
is evaluated --(1) && (++k)
++k
is evaluated --(1) && (1)
;- Evaluates true;
这篇关于请解释一下precedence与放大器之间的明显冲突;放大器&;和||与前任pression的实际结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!