Ordering of boolean values

2020-07-02 09:21发布

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

7条回答
可以哭但决不认输i
2楼-- · 2020-07-02 09:46

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.h

Seems, 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 be b < true, b < false if char is signed

For me (int)(bool) -1 is 1 even in C, so bool is defined as not char

查看更多
登录 后发表回答