Boolean datatypes (really about enum types and the PCC)

guy at sun.UUCP guy at sun.UUCP
Fri Jun 20 05:14:41 AEST 1986


> The proposed draft ANSI C standard doesn't seem to require that compilers
> treat enums as anything other than ints.  If people are writing programs
> which employ enums strictly as ints, the utility of enums in type
> verification seems to be nil and compiler warnings will just be obnoxious.

I wouldn't say their utility was nil.  I don't know how many people
literally use them strictly as ints; it would seem kind of silly to set some
"int" variable to 33 by doing

	enum bag_of_numbers { thirty_three = 33, sixty_six = 66, ... };

	variable = thirty_three;

I suspect that in most cases an "enum" is being used roughly the same way
it's used in other languages, to represent a member of a collection of named
objects.  The difference in C is that you can bind values to these names,
either because the values are imposed by some external agency (error codes
in a protocol or from an external device, etc.) or because one wishes to
implement some function whose domain is the set of values for that "enum"
using some efficient trick involving arithmetic on the underlying value of
the "enum".  As such,

	enum apples { jonathan, ... } apple;
	enum oranges { jaffa, ... } orange;

	if (apple == orange) {
		...
	}

would be, well, comparing apples and oranges, and should get a warning.

You can use casts to override this;

	if (apple == (enum apples) orange)

should not give a warning.

Another reason why "enum"s need to be treated as ints is that you may want
to use them as subscripts.  Other languages handle this by supporting
subrange types and treating an array as a mapping from some integral or
enumerated type to some other type, so that you declare the bounds of an
array by giving the type to be used as an index.  You don't do this in C
(for one thing, C doesn't support subranges, so you can't declare a
10-element array by saying its index is the subrange 1..10; for another
thing, C's notion of array indexing is a bit strange), so you can't say
"this array has "enum apples" as its subscript.

I hope future ANSI C compilers don't treat "enum"s totally like arrays.  For
one thing, they'd better not put "this is just an integral type of some
particular size" in the debugger's symbol table; they should specify that
it's an enumerated type and give the names of the type's values.
-- 
	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