Ordering of boolean values

后端 未结 7 1731
醉酒成梦
醉酒成梦 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:43

    Boolean values are ordered such that false is smaller than true. According to the standard, a bool can only hold two values: true and false, so the conversions in (bool)-1 should have yielded true (as all non-0 values when converted to bool are true). That is the behavior in clang and g++-4.7.

    The actual comparison (I believe) is done on int after the bool is promoted, and it seems that the compilers you tested avoided the intermediate step of converting through bool and just promoted the actual bool value.

提交回复
热议问题