As far as I can see there are 3 ways to use booleans in c
#defin
I used to use the #define because they make code easier to read, and there should be no performances degradation compared to using numbers (0,1) coz' the preprocessor converts the #define into numbers before compilation. Once the application is run preprocessor does not come into the way again because the code is already compiled.
BTW it should be:
#define FALSE 0
#define TRUE 1
and remember that -1, -2, ... 2, 3, etc. all evaluates to true.
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.
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:
if (variable == TRUE)
{
...
}
instead of:
if (variable)
{
...
}
Any int other than zero is true; false is zero. That way code like this continues to work as expected:
int done = 0; // `int` could be `bool` just as well
while (!done)
{
// ...
done = OS_SUCCESS_CODE == some_system_call ();
}
IMO, bool
is an overrated type, perhaps a carry over from other languages. int
works just fine as a boolean type.
You can test if bool is defined in c99 stdbool.h with
#ifndef __bool_true_false_are_defined || __bool_true_false_are_defined == 0
//typedef or define here
#endif
I don't know you specific situation. Back when I was writing C programs, we have always used #2.
#define FALSE = 0
#define TRUE = !FALSE
This might be otherwise under alien platform to DOS or Intel-based processors. But I used to use both C and ASM together writing graphic libraries and graphical IDE. I was a true fan of Micheal Abrash and was intending to learn about texture mapping and so. Anyway! That's not the subject of the question here!
This was the most commonly used form to define boolean values in C, as this headerfile stdbool.h did not exist then.