简体   繁体   English

基本逻辑运算符问题

[英]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. 现在是处决的一击而过。

  1. k starts at 5. k从5开始。
  2. ++k<5 advances k to 6, which is not <5 . ++k<5k提升到6,而不是 <5
  3. The second half of the && expression is never evaluated, because 0 && ANYTHING == 0 . &&表达式的后半部分从不求值,因为0 && ANYTHING == 0
  4. Because the left hand side of the || 因为||的左侧 is 0, the right hand side is not short circuited. 为0时,右侧短路。 It must be evaluated. 必须对其进行评估。
  5. ++k<=8 advances k to 7, which is <=8 . ++k<=8前进k到7,其 <=8
  6. Total conditional evaluates to 1 because right hand side of || 因为||右侧,所以总条件求值为1 is 1. 是1。
  7. The "then" clause of the if statement is executed. if执行if语句的“ then”子句。
  8. Current value of k , which is 7, is printed. 打印k当前值为7。
  9. The program returns 0, and terminates. 程序返回0,然后终止。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM