Ordering of boolean values

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

    In C++ (and I suspect in C as well), bools compare exactly as if false were 0 and true were 1. And if the type is bool, no values other than true and false are possible.

    When comparing bool to other numeric types, it will convert to int, again with false converting to 0 and true converting to 1.

    Edit: Both C++ and stdbool.h in C99 also force boolean values to be either 0 (false) or 1 (true) - bool b = -1; sets the value of b to 1. Since 1 < 1 and 1 < 0 are both false, the inequalities in the question are correct.

    Edit: (by James) Except that the above edit isn't really correct, at least for C++. A bool doesn't have a value of 0 or 1, it has a value of false or true. It's only when it is promoted to int that the conversion creates the values of 0 and 1.

    And as Konrad has pointed out, there is no conparison of bool values. The "usual arithmetic conversions" occur for the comparison operators, which means integral promotion on both of the operands, which means bool converts to int (as does char or short... or an enum).

    All of which is rather technical. In practice, you can remember that false < true, or you can consider false is 0 and true is 1, whichever works best for you. The only important thing to remember is that a bool can have no other values.

    (Interestingly, I don't think that the bit patterns of a bool are imposed by the standard. An implementation could use the bit patterns 0x55 and 0xAA, for example, as long as all conversions to an integral type gave 0 and 1, conversion to bool always gave the appropriate value, etc. Including zero initialization of static variables.)

    And one final note: bool b = -1; sets b to -1 != 0 (which is true, not 1, but of course, true will convert to 1 in any numeric context.

提交回复
热议问题