Using boolean values in C

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

    First things first. C, i.e. ISO/IEC 9899 has had a boolean type for 19 years now. That is way longer time than the expected length of the C programming career with amateur/academic/professional parts combined when visiting this question. Mine does surpass that by mere perhaps 1-2 years. It means that during the time that an average reader has learnt anything at all about C, C actually has had the boolean data type.

    For the datatype, #include , and use true, false and bool. Or do not include it, and use _Bool, 1 and 0 instead.


    There are various dangerous practices promoted in the other answers to this thread. I will address them:

    typedef int bool;
    #define true 1
    #define false 0
    

    This is no-no, because a casual reader - who did learn C within those 19 years - would expect that bool refers to the actual bool data type and would behave similarly, but it doesn't! For example

    double a = ...;
    bool b = a;
    

    With C99 bool/ _Bool, b would be set to false iff a was zero, and true otherwise. C11 6.3.1.2p1

    1. When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1. 59)

    Footnotes

    59) NaNs do not compare equal to 0 and thus convert to 1.

    With the typedef in place, the double would be coerced to an int - if the value of the double isn't in the range for int, the behaviour is undefined.

    Naturally the same applies to if true and false were declared in an enum.

    What is even more dangerous is declaring

    typedef enum bool {
        false, true
    } bool;
    

    because now all values besides 1 and 0 are invalid, and should such a value be assigned to a variable of that type, the behaviour would be wholly undefined.

    Therefore iff you cannot use C99 for some inexplicable reason, for boolean variables you should use:

    • type int and values 0 and 1 as-is; and carefully do domain conversions from any other values to these with double negation !!
    • or if you insist you don't remember that 0 is falsy and non-zero truish, at least use upper case so that they don't get confused with the C99 concepts: BOOL, TRUE and FALSE!

提交回复
热议问题