[英]Basic logical operator question
#include <stdio.h>
int main()
{
int k=5;
if(++k < 5 && k++ / 5 || ++k <= 8)
{
printf("%d",k);
}
return 0;
}
Why is the output 7 and not 8?(I am a beginner in programming so please bear with me.) 为什么输出7而不是8?(我是编程的初学者,请耐心等待。)
Operator precedence and logical expression short circuit evaluation . 运算符优先级和逻辑表达式短路评估 。
The &&
in your logical condition binds more tightly than ||
逻辑条件中的
&&
绑定比||
绑定更紧密 , so your conditional is equivalent to: ,因此您的条件等同于:
((++k<5 && k++/5) || ++k<=8)
It's easier to read code when it is presented in a structured way, like this: 以结构化的方式呈现代码时,更容易阅读代码,如下所示:
int main() {
int k=5;
if ((++k<5 && k++/5) || ++k<=8) {
printf("%d",k);
}
return 0;
}
And now a blow-by-blow of the execution. 现在是处决的一击而过。
k
starts at 5. k
从5开始。 ++k<5
advances k
to 6, which is not <5
. ++k<5
将k
提升到6,而不是 <5
。 &&
expression is never evaluated, because 0 && ANYTHING == 0
. &&
表达式的后半部分从不求值,因为0 && ANYTHING == 0
。 ||
||
的左侧 is 0, the right hand side is not short circuited. ++k<=8
advances k
to 7, which is <=8
. ++k<=8
前进k
到7,其为 <=8
。 ||
||
右侧,所以总条件求值为1 is 1. if
statement is executed. if
执行if
语句的“ then”子句。 k
, which is 7, is printed. k
当前值为7。 It's also worth noting that the second half of your &&
clause is perhaps not doing what you intended. 还值得注意的是,
&&
子句的后半部分可能未达到您的预期目的。 k++/5
is integer division, and since k>5
at all times, k++/5
will always be >=1
and thus always true. k++/5
是整数除法,并且由于k>5
始终都>=1
k++/5
,因此k++/5
总是>=1
,因此始终为true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.