Is it better to do this
#define INT_TRUE 1
#define INT_FALSE 0
int someFunctionalityIsEnabled = INT_TRUE;
or this?
int someFunctionalityIsEnabled = 1;
It can be safely assumed that false will always be zero and true will be non-zero.
3
It can be safely assumed that false will always be zero and true will be non-zero.
In this case, your question is almost pointless: If you are sure that everyone reading your code knows how “true” and “false” are represented as numbers, then you might not need those #define
macros.
Positive side effect of these #define
s. I am saying “almost” because these #define
s still have value: Without names like TRUE
and FALSE
, choosing sensible variable names becomes somewhat more important. For example:
int is_enabled = 1;
int age_in_years = 1;
How can you tell which variable stores a boolean value, and which an integer number? By looking at the variable names. Now, how about this?:
int is_enabled = TRUE;
int age_in_years = 1;
The #define
s add some redundancy (besides well-chosen variable names) that helps you recognise the “real” type of those int
variables more easily.
For this reason of added clarity, I would recommend using such #define
s, or if you are using a C99-conforming compiler, #include <stdbool.h>
.
Negative side effect of these #define
s. There’s also a bad side to declaring a TRUE
literal. You are saying that “true” may be represented by “any non-zero integer”. Defining TRUE
as being equivalent to 1
is therefore inaccurate, since that is only one out of many possible values meaning “true”. (FALSE
doesn’t suffer from this.) This leads to the somewhat absurd consequence that writing is_enabled == FALSE
will work as expected, but is_enabled == TRUE
might not. There’s two ways out of this issue:
-
DO NOT ever compare boolean values using
==
or!=
. Instead,- DO write
is_enabled
instead ofis_enabled == TRUE
, and - DO write
!is_enabled
instead ofis_enabled == FALSE
.
- DO write
-
CONSIDER re-defining “true” as “the integer number 1” instead of as “any non-zero integer number”. (I would not, since it contradicts how C interprets integers as boolean values… but it’s a theoretical possibility.)
I recommend you go with #1 for the reason mentioned.
5
The result is the same. Using the
#define TRUE 1
#define FALSE 0
is more verbose, but it may make your code more readable for future generations (of programmers or your own brain cells) who are maintaining the application and trying to decipher the code.
1