Printf even though it shouldn't

后端 未结 2 1643
梦谈多话
梦谈多话 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: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 ||.

提交回复
热议问题