It happens so often, I’m curious as to why the C language standard I/O header file doesn’t define TRUE and FALSE. Then again, what is TRUE and FALSE to a programming language — or to a computer? Why is this value true and that value false in the first place?
The C language treats any non-zero value as a logical TRUE. The value zero is FALSE.
Yes, even negative values are TRUE. This concept throws me. Once upon a time, I must have worked in a programming language where -1 was FALSE. That’s not the case in C, as the following code demonstrates.
#include <stdio.h> int main() { int tf; for(tf=-5;tf<=5;tf++) { if(tf) printf("%d is TRUE\n",tf); else printf("%d is FALSE\n",tf); } return(0); }
Here’s sample output:
-5 is TRUE
-4 is TRUE
-3 is TRUE
-2 is TRUE
-1 is TRUE
0 is FALSE
1 is TRUE
2 is TRUE
3 is TRUE
4 is TRUE
5 is TRUE
I could have extended the range for variable tf
to the entire int spectrum. The output would be similar, with millions of TRUE values and only one FALSE value, zero.
The advantage of this arrangement is that you can use a single value as a condition in an if statement or while loop, or anywhere a comparison is required. Non-zero values evaluate to TRUE.
If you’re going to declare TRUE and FALSE constants in your code, do it this way:
#define FALSE 0
#define TRUE !FALSE
FALSE
is always zero. TRUE
is any value that is “not” zero, or !FALSE
. If you define TRUE as equal to 1, then you can mess up some conditions elsewhere in the code where a value other than 1 is legitimately considered to be TRUE.