Using boolean values in C

前端 未结 18 2053
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 12:51

C doesn\'t have any built-in boolean types. What\'s the best way to use them in C?

18条回答
  •  没有蜡笔的小新
    2020-11-22 13:17

    Just a complement to other answers and some clarification, if you are allowed to use C99.

    +-------+----------------+-------------------------+--------------------+
    |  Name | Characteristic | Dependence in stdbool.h |        Value       |
    +-------+----------------+-------------------------+--------------------+
    | _Bool |   Native type  |    Don't need header    |                    |
    +-------+----------------+-------------------------+--------------------+
    |  bool |      Macro     |           Yes           | Translate to _Bool |
    +-------+----------------+-------------------------+--------------------+
    |  true |      Macro     |           Yes           |   Translate to 1   |
    +-------+----------------+-------------------------+--------------------+
    | false |      Macro     |           Yes           |   Translate to 0   |
    +-------+----------------+-------------------------+--------------------+
    

    Some of my preferences:

    • _Bool or bool? Both are fine, but bool looks better than the keyword _Bool.
    • Accepted values for bool and _Bool are: false or true. Assigning 0 or 1 instead of false or true is valid, but is harder to read and understand the logic flow.

    Some info from the standard:

    • _Bool is NOT unsigned int, but is part of the group unsigned integer types. It is large enough to hold the values 0 or 1.
    • DO NOT, but yes, you are able to redefine bool true and false but sure is not a good idea. This ability is considered obsolescent and will be removed in future.
    • Assigning an scalar type (arithmetic types and pointer types) to _Bool or bool, if the scalar value is equal to 0 or compares to 0 it will be 0, otherwise the result is 1: _Bool x = 9; 9 is converted to 1 when assigned to x.
    • _Bool is 1 byte (8 bits), usually the programmer is tempted to try to use the other bits, but is not recommended, because the only guaranteed that is given is that only one bit is use to store data, not like type char that have 8 bits available.

提交回复
热议问题