Using true and false in C

后端 未结 15 1808
情书的邮戳
情书的邮戳 2020-12-01 01:52

As far as I can see there are 3 ways to use booleans in c

  1. with the bool type, from then using true and false
  2. defining using preprocessor #defin
相关标签:
15条回答
  • 2020-12-01 02:13

    Just include <stdbool.h> if your system provides it. That defines a number of macros, including bool, false, and true (defined to _Bool, 0, and 1 respectively). See section 7.16 of C99 for more details.

    0 讨论(0)
  • 2020-12-01 02:17

    1 is most readable not compatible with all compilers.

    No ISO C compiler has a built in type called bool. ISO C99 compilers have a type _Bool, and a header which typedef's bool. So compatability is simply a case of providing your own header if the compiler is not C99 compliant (VC++ for example).

    Of course a simpler approach is to compile your C code as C++.

    0 讨论(0)
  • 2020-12-01 02:18

    There is no real speed difference. They are really all the same to the compiler. The difference is with the human beings trying to use and read your code.

    For me that makes bool, true, and false the best choice in C++ code. In C code, there are some compilers around that don't support bool (I often have to work with old systems), so I might go with the defines in some circumstances.

    0 讨论(0)
  • 2020-12-01 02:19

    I prefer (1) when i define a variable but in expressions i never compare against true and false just take the implicit C definition of if(flag) or if(!flag) or if(ptr). Thats the C way to do things.

    0 讨论(0)
  • 2020-12-01 02:20

    I usually do a:

    typedef enum {FALSE = 0, TRUE} boolean;
    
    0 讨论(0)
  • 2020-12-01 02:27

    Just use 0 or 1 directly in the code.

    For C programmers, this is as intuitive as true or false.

    0 讨论(0)
提交回复
热议问题