比较运算符的数学式链接-如“if((5<j<=1))"

2021-12-12 00:00:00 c if-statement comparison-operators c++
int j=42;
if( (5<j<=1) ) {
    printf("yes");
} else {
    printf("no");
}

输出:

yes

为什么输出yes?
条件不是只对了一半吗?

Why does it output yes?
Isn't the condition only half true?

推荐答案

C 不理解类似数学的语法,所以

C does not understand math-like syntax, so

if(1<j<=5)

没有按照您的预期和想要的方式进行解释;应该是

is not interpreted as you expect and want; it should be

if (1 < j && j <= 5)

或类似的.

正如在其他答案中所解释的,表达式的计算方式为

As explained in other answers, the expression is evaluated as

 ((1 < j) <= 5)

 =>  ("true" <= 5)

 =>  "true"

其中true"(布尔值)隐式转换为 1,如 explaneid,例如此处,也参考了标准,这解释了为什么true"必须是less"比" 5(尽管在 C 中谈论从 bool 到 int 的隐式转换"可能并不完全正确)

where "true" (boolean value) is implicitly converted to 1, as explaneid e.g. here, with references to standards too, and this explain why "true" has to be "less than" 5 (though in C might not be totally correct to speak about "implicit conversion from bool to int")

相关文章