Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering of boolean values

Tags:

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

Alternatively, explain the behaviour of this code:

#ifndef __cplusplus
#include <stdbool.h>
#endif
#include <stdio.h>

int main() {
    bool b = -1;
    if(b < true) {
        printf("b < true\n");
    }
    if(b < false) {
        printf("b < false\n");
    }
    if(true < false) {
        printf("true < false\n");
    }
    if(false < true) {
        printf("false < true\n");
    }
}

Under MSVC version 10, compiled as C++ code, GCC 4.6.3-ubuntu5 compiled as C code and G++ 4.6.3-1ubuntu5 compiled as C++ code, all you get is

false < true

That is, the following inequalities are all false:

(bool)-1 < true
(bool)-1 < false
true < false

And the following is true:

false < true
like image 619
Tom Avatar asked Aug 14 '12 11:08

Tom


1 Answers

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.

like image 200
James Kanze Avatar answered Nov 15 '22 22:11

James Kanze