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
In C++ (and I suspect in C as well),
bools compare exactly as iffalsewere0andtruewere1. And if the type isbool, novalues other than
trueandfalseare possible.When comparing
boolto other numeric types, it will convert toint,again with
falseconverting to0andtrueconverting to1.Edit: Both C++ and
stdbool.hin C99 also force boolean values to be either 0 (false) or 1 (true) –bool b = -1;sets the value ofbto 1. Since1 < 1and1 < 0are 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
booldoesn’t have a value of 0 or 1, it has a valueof
falseortrue. It’s only when it is promoted tointthat theconversion creates the values of
0and1.And as Konrad has pointed out, there is no conparison of
boolvalues.The “usual arithmetic conversions” occur for the comparison operators,
which means integral promotion on both of the operands, which means
boolconverts toint(as doescharorshort… or an enum).All of which is rather technical. In practice, you can remember that
false<true, or you can considerfalseis 0 andtrueis 1,whichever works best for you. The only important thing to remember is
that a
boolcan have no other values.(Interestingly, I don’t think that the bit patterns of a
boolareimposed by the standard. An implementation could use the bit patterns
0x55and0xAA, for example, as long as all conversions to anintegral type gave 0 and 1, conversion to
boolalways gave theappropriate value, etc. Including zero initialization of static
variables.)
And one final note:
bool b = -1;setsbto-1 != 0(which istrue, not1, but of course,truewill convert to1in anynumeric context.