Putting aside the fact that since c99 the stdbool.h
has existed, when defining macros to handle Boolean types in C
is there any difference between the following?
#define FALSE 0
#define TRUE 1 // Option 1
#define TRUE !FALSE // Option 2
From the live example here, it doesn't seem to make a difference. Is there a technical benefit to either option? (Not including the fact that the second example would work better with c++ bool
objects.)
ISO C and C99 both define !
like so.
The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int . The expression !E is equivalent to (0==E).
So !0
evaluates to 1
. Given a standards compliant C compiler both your options will have the same result. In addition there's no runtime penalty, compilers will constant fold !0
to 1
at compile time.
If you want to take this to the logical extreme and make no assumptions about what true or false are...
#define TRUE (1==1)
#define FALSE (!TRUE)
This has the advantage of always being true no matter the language. For example, in shell 0 is usually considered "true" or "not an error".
This sort of thing is an anachronism from a time when C did not have an agreed upon standard. For example, the first edition of Code Complete advocates this on page 369. When it was published back in 1993 there was a good chance your C compiler was not going to be ISO compliant and stdbool.h did not exist. "Code Complete" is also intended for the polyglot programmer working in many different languages. Some, like shell and Lisp, define truth differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With