As far as I can see, there are three ways to use Booleans in C:
- with the bool type, from <stdbool.h> 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), and 1 is most readable not compatible with all compilers.
int i = 12 + 3 * 4;
; it'll just sayint i = 24;
. Worrying about performance like that a common problem, don't feel bad. Optimizations comes last, and when it does come you have to time your code and look at the assembly output, not guess. Even if it did cost a cycle, I'd go for the most readable solution. Only when it proved to be a – Refugiorefulgence(x == TRUE)
is not the same as(x)
. The former is true only ifx
holds the value ofTRUE
. The latter is true for any non-zero value. – Observerif(foo == TRUE)
orif(foo == FALSE)
, which is an atrocity in most languages, but even more so in C, where any scalar value!= 0
is considered to be true in boolean contexts; for similar, but less severe reasons, I dislikeif(foo != NULL)
andif(foo == NULL)
for pointers; as this can't introduce bugs as a comparison toTRUE
can, it's merely a matter of taste, but usingif(foo)
andif(!foo)
for any scalar value is imo more in tune with the C language look-and-feel – Chlorophyll!(FALSE)
logical negation? Otherwise if!
were bitwise, it would evaluate to-1
, no? – Crockett