Definition of boolean type

Rick Clements rickc at pogo.GPID.TEK.COM
Tue Feb 28 07:01:40 AEST 1989


In article <1989Feb10.092449.20875 at sq.uucp> msb at sq.com (Mark Brader) writes:
}} 1.	typedef short bool;
}} 2.	typedef char bool;
}} 3.	typedef enum {FALSE=0, TRUE=1} bool;

}The last is nicely self-documenting, as long as you understand that the
}language will never enforce it for you, but as you noted, some existing
}compilers have problems with it.  (In the ANSI draft, all the constructs
}you want do work.)

}However, for ordinary use I prefer none of these.  My booleans are int
}when they are scalars or in small arrays: I let the computer work in its
}favorite size.

I always use chars.  This lets the machine I am working on (an 68HC11)
work in its favorite size.  Everyone assumes an int is the natural size
of the machine, but an int is at least 16 bits.

}Basically I reserve typedefs for occasions when they will significantly
}enhance either brevity or modularity.  Typedefing boolean does neither,
}but only adds a bit (no pun intended) of documentation.  This can be done
}just as well with a comment beside the declaration, or better yet, by
}choosing a suitable name for the variable itself.

I perfer to use typedef's for the extra documentation.  Also, if I work
on code that might be ported, it is easy to change to match the machine.

}The worst thing a person who defines TRUE and FALSE can do, though, is
}"if (x == TRUE)".  This is a true abomination.  If the variable is true to
}its logical type, it is true that this is equivalent to "if (x)", but it's
}also true that it's very likely to be slower.  And if the variable is
}*not* true to its logical type, i.e. if it may sometimes have a value
}other than 0 or 1, then the code becomes extremely tricky for the logical
}programmer to debug!

With the compiler I am currently using, I use "if (x == FALSE)" or
"if (x != FALSE).  This doesn't have an ambiguity because of multiple
true values.  The compiler I am using generates LESS code this way. 
("if (x)" causes it to go to the work of converting it to a 1 or 0
with some less than efficient code.  That is ignoring the fact the
whole process it unneeded.)  PROM space is tight, so this becomes 
important.  It also helps when you want to get an entire sequence on
a logic analyzer trace.
-- 
Rick Clements (RickC at pogo.GPID.TEK.COM)



More information about the Comp.lang.c mailing list