Boolean datatypes

Guy Harris guy at sun.uucp
Sat Jun 14 04:09:51 AEST 1986


> At the risk of being flamed, I've been using enums for a proper boolean
> datatype for years:
> 
> 	typedef enum { false=0,true } bool;
> ...
> This has _lots_ of advantages over the usual #defines - especially with
> a decent compiler which will barf on constructs like:
> 
> 	flag=10;	 /* correct syntax error,10 is neither true nor false */

Well, I doubt the compiler would claim that it was a syntax error; PCC
complains about an "enumeration type clash" (which is a warning, rather than
an error).  This is an advantage of "enum"s, though, even though it's just a
warning.  If you fix some bugs in "lint", it even checks that you aren't
passing an "enum" to a routine expecting an "int" or another "enum", or an
"int" to a routine expecting an "enum".

Also, if you use "enum"s rather than #define constants, a reasonable
symbolic debugger will, when asked to print an "enum" variable's value,
print it by its "enum" element name ("dbx" does, I don't know about the
others).

However, there is one problem with using "enum"s for a boolean type;
"Boolean" expressions in C have type "int", not "enum", so

	bool flag = (foobar == 33);

will cause an "enumeration type clash" error; you have to cast the
expression to type "bool" to silence the compiler.

Note that "enum"s, according to the current C draft, are basically integral
types; this means that assignments of "int"s to "enum"s are legal, although
this doesn't mean the compiler can't produce a warning.

> Many current C compilers now implement enums properly (i.e. each enumeration
> is a distinct type)

What C compilers don't?

> ...yet they are hardly ever used. Any comments why not ?

Habit?
-- 
	Guy Harris
	{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
	guy at sun.com (or guy at sun.arpa)



More information about the Comp.lang.c mailing list