Enums as Indices
Guy Harris
guy at sun.uucp
Fri Feb 21 06:14:20 AEST 1986
> Second, I feel that ENUM's are merely a way of writing #defines with a
> bit of type checking thrown in (thus the error). One of the things you
> can do with integers is use them for subscripts. I can imagine a
> statement like `wavelenth[RED] = however_many_angstroms_red_really_is'. ...
> An expression such as `wavelength['RED'] = ...' is currently legal altho
> not recommended (portability).
Unfortunately, as pointed out such an expression is not legal according to
PCC, at least, although ANSI C indicates that "enum"s are really just funny
names for "int"s and presumably allows their use as subscripts. (This means
that the type checking may go away, although it'd be nice to have it at
least issue a warning on a type clash; consider the definition
typedef enum { READ, WRITE } op_type;
typedef enum { BYTES, CHARACTERS } io_mode;
int funny_io(int, char *, int, op_type, io_mode);
which could catch errors like
ntransferred = funny_io(fd, buf, count, BYTES, READ);
) Conceptually, an array of type "x" using type "y" as a subscript is a
function from the set of members of type "x" to the members of type "y".
However, C doesn't permit you to specify "y" directly as a type, so
you can't do
enum color { red, orange, yellow, green, blue, indigo, violet };
float wavelength[enum color];
to indicate that the valid subscripts for "wavelength" are members of the
enumeration type "enum color" and to tell it to allocate 7 elements for the
array. Things would get even messier if you defined a sparse enumeration;
should it allocate array elements for all the missing elements, or implement
the array differently from a dense one? Furthermore, to make arrays indexed
by a subset of the integers work, you'd have to add subrange types to C;
this might be a nice thing to do, but it drags in a lot of additional
baggage.
--
Guy Harris
{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
guy at sun.arpa (yes, really)
More information about the Comp.lang.c
mailing list