【问题标题】:What's the behaviour of the Comparison operator? [duplicate]比较运算符的行为是什么? [复制]
【发布时间】:2012-10-19 11:05:38
【问题描述】:

可能重复:
Double comparison

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&lt;=x&lt;=9) 时没有给出error

【问题讨论】:

  • if((0&lt;=x)&lt;=9)->if(false&lt;=9)->if(0&lt;=9)
  • 类似于(0 * x * 9)
  • 我看不出编译器有任何抱怨的理由……它是一个有效的语法

标签: c++ c comparison operators


【解决方案1】:

在 C 中,布尔值只是普通整数。在布尔上下文中,0 为假,所有其他值都为真。在这种情况下,

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

【讨论】:

    猜你喜欢
    • 2016-03-22
    • 1970-01-01
    • 2018-01-15
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多