Ordering of boolean values

后端 未结 7 1755
醉酒成梦
醉酒成梦 2021-02-18 17:02

Under C++ or from C99, how is the less-than operator < defined for boolean values?

Alternatively, explain the behaviour of

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-18 17:38

    Here is an explaination, I haven't checked with the standard though. From your experiments it seems that the "<" operator is not defined for boolean values. What is compared is the unsigned ints that the booleans are converted to. In theory it could be possible that the standard doesn't guarantee that all "true" booleans are converted to the same value. And -1 is converted to the largest unsigned int.

    As another experiment, the following code

    #include 
    
    int main()
    {
    std::cout<< (((bool)1) == true) << "\n";
    std::cout<< (((bool)2) == true) << "\n";
    std::cout<< (((bool)0) == false) << "\n";
    std::cout<< (((bool)1) == false) << "\n";
      return 0;
    }
    

    prints 1 1 1 0

    So any nonzero value is "true".

提交回复
热议问题