Using boolean values in C

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

    From best to worse:

    Option 1 (C99)

    #include 
    

    Option 2

    typedef enum { false, true } bool;
    

    Option 3

    typedef int bool;
    enum { false, true };
    

    Option 4

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

    Explanation

    • Option 1 will work only if you use C99 and it's the "standard way" to do it. Choose this if possible.
    • Options 2, 3 and 4 will have in practice the same identical behavior. #2 and #3 don't use #defines though, which in my opinion is better.

    If you are undecided, go with #1!

提交回复
热议问题