Why are C booleans called _Bool?

后端 未结 3 1434
旧时难觅i
旧时难觅i 2021-02-12 13:03

Why does C use the word _Bool to define boolean values? Whereas they use the word float for floats and not _Float?

Furthermore, wh

3条回答
  •  我在风中等你
    2021-02-12 13:07

    C did not originally have a Boolean type, it was added in the 1999 version of the language (C99). At that point, C++ was already standardized (in 1998) to use the type bool, with keywords false and true. To keep the C Boolean type separate from the one in C++, as well as preventing the new name from breaking old C code, it was named _Bool.

    The reason why it was named with an underscore followed by an upper-case letter, is because such an identifier was already guaranteed not to exist in compiler, library or user code, by 7.1.3:

    All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.

    "Reserved for any use" meaning reserved for future versions of the C language.

    Therefore, all new language keywords that have been added to the language since C99 are named with underscore followed by first letter upper-case. Other examples from C99 are the types _Complex and _Imaginary.


    For the cases where code compatibility with C++ was desired, the header was created. It contains the macro bool, which expands to _Bool. And also the macros false and true that expand to 0 and 1.

    Though note that booleans are not fully integrated in the C language, as they are in C++. In C++, an expression such as a == b gives a result of type bool, with the value true or false. In C it gives a result of type int, with the value 1 or 0. This is for backwards-compatibility reasons with old C code.

提交回复
热议问题