As far as I can see there are 3 ways to use booleans in c
- with the bool type, from then using true and false
- defining using preprocessor
#define FALSE 0 ... #define TRUE !(FALSE)
- Just to use constants directly, i.e. 1 and 0
are there other methods I missed? What are the pros and cons of the different methods?
I suppose the fastest would be number 3, 2 is more easily readable still (although bitwise negation will slightly add to overhead), 1 is most readable not compatible with all compilers.
Just include
<stdbool.h>
if your system provides it. That defines a number of macros, includingbool
,false
, andtrue
(defined to_Bool
, 0, and 1 respectively). See section 7.16 of C99 for more details.With the stdbool.h defined bool type, problems arise when you need to move code from a newer compiler that supports the bool type to an older compiler. This could happen in an embedded programming environment when you move to a new architecture with a C compiler based on an older version of the spec.
In summation, I would stick with the macros when portability matters. Otherwise, do what others recommend and use the bulit in type.
I prefer the third solution, i.e. using 1 and 0, because it is particularly useful when you have to test if a condition is true or false: you can simply use a variable for the if argument.
If you use other methods, I think that, to be consistent with the rest of the code, I should use a test like this:
instead of:
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.
No ISO C compiler has a built in type called
bool
. ISO C99 compilers have a type_Bool
, and a header which typedef'sbool
. 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++.
Just use 0 or 1 directly in the code.
For C programmers, this is as intuitive as true or false.