Booleans
Doing boolean logic in C is a little weird. There are, for example, no explicitly boolean variables -- instead, C represents 'TRUE' and 'FALSE' as the integers 1 and 0, respectively. In fact,
any integer other than 0 is 'TRUE' in the context of a boolean operator. Personally, I've always believed that this is because C was created in the early 70s, when almost everything was true. Anyway. Carrying on.
Programmers are notoriously lazy people; C programmers even more so. Often, you will encounter
really, really weird boolean logic in C, where a programmer has taken advantage of C's everything-not-zero-is-true rule in some clever (and highly confusing) fashion. As an example, let's try to puzzle out the value of
result
in this code:
int result;
if( (1 >= 2) || 7 )
result = 42;
else
result = 114;
printf("%d\n",result); // Prints ???
The interesting bit is that
if
expression. The computer first evaluates the left-hand side of the
||
, so let's start with that. Greater-than-or-equal (>=) is a relational operator; it takes two values of the same type and returns a boolean. In this case, it takes two integers (1 and 2) and returns FALSE, since 1 is not, in fact, greater than 2. But remember, in C FALSE is 0. So that
if
is essentially the same as:
int result;
if( 0 || 7 )
result = 42;
else
result = 114;
printf("%d\n",result); // Prints ???
Since the left hand side was false (0), we have to evaluate the right hand side to determine if the expression is true ("left
or right"). If the left hand side had been true (1), C would have
skipped the right hand side altogether, not even executing the code there. This is called
short-circuit evaluation, and it is as powerful as it is confusing.
In C, remember, anything that isn't 0 is TRUE, so 7 is TRUE, giving us:
int result;
if( 0 || 1 )
result = 42;
else
result = 114;
printf("%d\n",result); // Prints ???
Since an or (
||
) is true if
either the left hand or the right hand side (or both!) is true, the entire expression evaluates as TRUE (1), and
result
is set to 42.
A Trick
Since people don't normally think about true and false as integers when they're doing logic, most C programmers use a simple trick to add boolean types to C. Add these three lines to the header of your C program:
#define TRUE 1
#define FALSE 0
typedef int bool;
This defines a variable type called
bool
and two values, TRUE and FALSE. When you compile your program the compiler will translate all your boolean variables into integers, and all your TRUE and FALSE values into the appropriate integer values. To use your new
bool
type:
// ...meanwhile, in main()...
bool lies_about_my_mother = FALSE;
if( FALSE )
// We will never get here
if( TRUE || FALSE )
// We will always get here
if( lies_about_my_mother)
// Act!
--
TrevorFountain - 05 Dec 2008