Using boolean values in C

前端 未结 18 2070
被撕碎了的回忆
被撕碎了的回忆 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:09

    Here is the version that I used:

    typedef enum { false = 0, true = !false } bool;
    

    Because false only has one value, but a logical true could have many values, but technique sets true to be what the compiler will use for the opposite of false.

    This takes care of the problem of someone coding something that would come down to this:

    if (true == !false)
    

    I think we would all agree that that is not a good practice, but for the one time cost of doing "true = !false" we eliminate that problem.

    [EDIT] In the end I used:

    typedef enum { myfalse = 0, mytrue = !myfalse } mybool;
    

    to avoid name collision with other schemes that were defining true and false. But the concept remains the same.

    [EDIT] To show conversion of integer to boolean:

    mybool somebool;
    int someint = 5;
    somebool = !!someint;
    

    The first (right most) ! converts the non-zero integer to a 0, then the second (left most) ! converts the 0 to a myfalse value. I will leave it as an exercise for the reader to convert a zero integer.

    [EDIT] It is my style to use the explicit setting of a value in an enum when the specific value is required even if the default value would be the same. Example: Because false needs to be zero I use false = 0, rather than false,

提交回复
热议问题