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.
You can test if bool is defined in c99 stdbool.h with
I usually do a:
Whichever of the three you go with, compare your variables against FALSE, or false.
Historically it is a bad idea to compare anything to true (1) in c or c++. Only false is guaranteed to be zero (0). True is any other value. Many compiler vendors have these definitions somewhere in their headers.
#define TRUE 1
#define FALSE 0
This has led too many people down the garden path. Many library functions besides chartype return nonzero values not equal to 1 on success. There is a great deal of legacy code out there with the same behavior.
I would go for 1. I haven't met incompatibility with it and is more natural. But, I think that it is a part of C++ not C standard. I think that with dirty hacking with defines or your third option - won't gain any performance, but only pain maintaining the code.
Any int other than zero is true; false is zero. That way code like this continues to work as expected:
IMO,
bool
is an overrated type, perhaps a carry over from other languages.int
works just fine as a boolean type.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.