Definition of boolean type

Mark Brader msb at sq.uucp
Sat Feb 11 00:24:49 AEST 1989


> 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.  When the arrays become large enough to make space conser-
vation important, then of course I switch to char -- unless the array is so
big that I have to use shifts and masking to pack a boolean into each bit.

I prefer not to use typedefs for boolean for two reasons.  One is that I
couldn't make that decision to change types according to the array size
(unless I had two typedefs, of course).  The other reason is that I prefer
to use typedefs sparingly, because they conceal information that's
sometimes useful.  (I know that variable has a numerical value, but do I
need %d format to print it, or %ld or %u or %lu or %g...?)

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.

Thus, instead of this...		I prefer this...

boolean sex;				int is_female;	/* boolean */
struct country {			struct country {
	char name[CNAMELEN+1];			char name[CNAMELEN+1];
	boolean driving;			char drives_on_right;
							/* boolean */
} country[200];				} country[200];


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!

(All puns intended.  For the benefit of non-users of FORTRAN: "logical"
 is the name of the boolean type in that language.)

On the other hand, "is_female = TRUE;" is reasonable.  Some days I even
prefer it to the alternatives.


> use of all upper case to identify typedefs--bool vs. BOOL vs. Bool.

I figure typedefs are almost like macros, so I use BOOL.  Opinions vary.

Mark Brader, SoftQuad Inc., Toronto, utzoo!sq!msb, msb at sq.com
#define	MSB(type)	(~(((unsigned type)-1)>>1))



More information about the Comp.lang.c mailing list