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
For C++ just
false
<true
For C is more difficult to answer. I see
typedef char _Bool; /* For C compilers without _Bool */
in my stdbool.hSeems, that if compiler support
_Bool
, it works as in C++ and automatically converts to 0/1, but if not it should work as char and it'll beb < true
,b < false
if char is signedFor me (int)(bool) -1 is 1 even in C, so
bool
is defined as not char