Definition of boolean type

Doug Gwyn gwyn at smoke.BRL.MIL
Wed Feb 8 02:03:18 AEST 1989


In article <10 at dbase.UUCP> awd at dbase.UUCP (Alastair Dallas) writes:
>But what about a boolean type?
>Please excuse me if the standard discusses this as well, but I can think
>of several ways to handle booleans (and I've worked on code that used all
>three):
>1.	typedef short bool;
>2.	typedef char bool;
>3.	typedef enum {FALSE=0, TRUE=1} bool;
>I like the last one, but it requires a compiler that doesn't complain about
>constructs like:
>	bool flag = TRUE;
>	if (flag)

ANSI C compilers have to accept that.  Enums act just like ints in
expressions.  Some C compilers tried to make more full-fledged types
out of enumerations, with mixed success (generally unsatisfactory).
One occasionally still runs into such compilers, as you've noticed.

>While this means more typing*, I'm inclined to forgo the convenience of
>if (flag) in favor of the self-documentation of the explicit if (flag==TRUE).

If your Boolean variable is called `flag', that may be more intelligible,
but what about, for example,
	if ( too_many )
which is more readable the other way.  Generally I don't think of ==
or != as Boolean operators.

>I'm curious what the net thinks.

I don't know about the net; does it think?  My typedef for `bool' is
as an int, because that is the actual type of C Boolean expressions.

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

As a matter of style, if something is considered a (local) standard
extension to the base language, as with my <std.h> use of `bool' and
`pointer' (generic pointer type), then it should look like other
keywords.  Something that looks like a function should look like a
function (locally that means `TooMany()' etc.).  Manifest constants
generally should follow existing practice and appear as all-caps.
However, the most important thing is that your code be maintainable;
follow whatever stylistic guidelines best enforce that.



More information about the Comp.lang.c mailing list