True is a logical condition. It’s often written TRUE
just to confuse it with “true” which is a word that has other implications. But for programming, TRUE
generally means success. It’s the opposite of FALSE
, which generally means failure.
Traditionally, FALSE
is assigned the value zero. That’s not a hard fact, but it’s often the case.
When a function fails, it often returns zero. Or, more commonly, loops wind down from some number to zero, meaning that the loop has done or, specifically, the condition upon which the loop repeats is now FALSE
.
TRUE
, on the other hand, is defined as non-zero. It could be the value 1, which it often is, but it could also be any other value that’s not zero. In fact, in many of my C programs, I’ll define TRUE
and FALSE
this way:
#define FALSE 0
#define TRUE !FALSE
So FALSE
is zero and TRUE
is “not FALSE
.” That way the compiler can figure out what the value of TRUE is and my code still works. This method also frees you from having to bind the value TRUE to something specific.
As an example, suppose one compiler uses the value 0x0001 for TRUE
but another uses 0xFFFF for TRUE
. It happens. Or, more commonly, some function interprets any non-zero value as TRUE
. So 0x54 could be TRUE
, as could 0x52, 0x55, and 0x45.
Here’s a chunk of code:
#include <stdio.h> #define FALSE 0 #define TRUE !FALSE int main() { printf("True is %d\n",TRUE); printf("False is %d\n",FALSE); return(0); }
So how does the compiler calculate the value of TRUE
? Here’s the output:
True is 1
False is 0
That makes sense from a logical point of view, but also because the !
(bang or “not”) is a logical operator. The not value of zero is one.
Other ways to compute TRUE and FALSE also prove out those values:
#include <stdio.h> int main() { printf("True is %d\n",1==1); printf("False is %d\n",1!=1); return(0); }
In the above code, TRUE
and FALSE
aren’t declared as constants. They don’t have to be; the logical operations 1==1
and 1!=1
are used instead. The first operation is TRUE
and the second is FALSE
. The output is the same as for the first code:
True is 1
False is 0
The only exception I can find to the TRUE
is 1 and FALSE
is 0 paradigm is the return value passed to the operating system. In that case, zero has traditionally indicated a successful completion and any other value indicates some other condition.
The return code zero as TRUE
makes sense if you read the value returned as an “error level” instead of a success: Returning zero indicates a FALSE
, or no error. That’s my explanation, although I’d be interested in the history behind the return code to discover the real reason.