比较运算符的行为是什么?

What's the behaviour of the Comparison operator?

本文关键字:是什么 运算符 比较      更新时间:2023-10-16

可能的重复:
双重比较

int x=-1;
if(0<=x<=9)
std::cout<< "Without Logical operator";
if (0<=x && x<=9)
std::cout<< "With Logical operator";

我知道第二个if,它运行良好。在第一个if条件下发生了什么。它进入第一个if,而x-1以及为什么编译器在使用(0<=x<=9)时没有给出error

在C中,布尔值只是纯整数。在布尔上下文中,0为false,所有其他值均为true。在这种情况下,

(0 <= x <= 9)   ==
((0 <= x) <= 9) == // the (0 <= x) evaluates to 0, which is false in boolean context
(0 <= 9)        ==
1 (true)