为什么输出在代码中不会是这个? [英] Why the output won't be this in the code?
问题描述
#include <stdio.h>
int main(void) {
int i = -3, j = 2, k = 0, m;
m = ++i && ++j || ++k;
printf("%d %d %d %d\n",i,j,k,m);
return 0;
}
我试图了解C语言中操作符的关联性和优先级.在这里,输出结果为-2 3 0 1
,但我认为输出应该为-2 3 1 1
,因为k
也已预先递增.为什么那不是答案?谢谢!
I am trying to learn about associativity and precedence of operators in C. Here, The output comes out to be -2 3 0 1
, but I think the output should be -2 3 1 1
because k
is also pre-incremented. Why that won't be the answer? Thanks!
推荐答案
||
具有短路评估功能,这意味着仅当左侧为false
时,右侧才被评估.在您的情况下,不会发生这种情况,因为i
和j
的值在递增后都不同于0
,因此++k
不会执行
the ||
has short-circuit evaluation, which means that the right hand side gets evaluated only if the left hand side is false
. In your case this doesn't happen since both i
and j
have values different than 0
after being incremented, so the ++k
doesn't get executed
当您有一个&&
且LHS表达式的计算结果为false
The same behavior occurs when you have a &&
in which the LHS expressions evaluates to false
这篇关于为什么输出在代码中不会是这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!