As far as I can see there are 3 ways to use booleans in c
#defin
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.
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++.
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.
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.
I usually do a:
typedef enum {FALSE = 0, TRUE} boolean;
Just use 0 or 1 directly in the code.
For C programmers, this is as intuitive as true or false.