Printf even though it shouldn't

后端 未结 2 1644
梦谈多话
梦谈多话 2021-01-28 08:15

I have this part of an if statement and I\'m getting a weird output.

int x = 10;

if(1 < x < 5){
    printf(\"F\\n\");
}

Why does it prin

相关标签:
2条回答
  • 2021-01-28 08:35

    If you are using C, you should have broken down the condition into two arguments :

        if ( x > 1 && x < 5) {
            printf("F\n");
        }
    
    0 讨论(0)
  • 2021-01-28 08:42

    In C, you can't chain comparisons like that. The expression 1 < x < 5 is evaluated as (1 < x) < 5: so for x = 10, the expression is (1 < 10) < 5. (1 < 10) is true, which C represents as the value 1, so the expression reduces to 1 < 5. This is always true, and your printf() if executed.

    As level-999999 says, in C you need to explicitly combine single comparisons with && and ||.

    0 讨论(0)
提交回复
热议问题