Enums

Chris Gray cg at myrias.UUCP
Tue Oct 1 04:21:16 AEST 1985


Actually, it's not hard at all to come up with a model for enum's that is
both efficient and useful. I have such a model implemented in a compiler I
wrote (not a C compiler). Type 'bool' is also built-in, so I don't have any
need to allow an enum type to be used directly in 'if's, 'while's, etc.

First, don't allow the programmer to specify specific values for the enum
constants. This, in my opinion, violates the whole point of enumerations
(a list of specific values which are the only values allowed - there is no
implication about what the values look like). C's allowing two names to
have the same value seems very dangerous. Usefulness is added, and not too
much danger, by adding ordering to the enumeration type, such that later
names in the list are greater than previous ones. By defining that each is
exactly 1 greater than the previous, we can allow the following:

    ordering is clearly defined for all legal values
    adding/subtracting an integer simply yields another enumeration value
        which is correspondingly further along or back in the list of names.
	(we politely ignore out-of-range values here just as we do for
	integer overflows)
    converting to integers is done by subtracting the first value, and
        converting from integer is done by adding the first value. e.g.
	
	type FRUIT = enum {APPLE, PEAR, ORANGE, BANANA};
	type DIRECTION = enum {NORTH, EAST, SOUTH, WEST};
	FRUIT f1, f2;
	int i1, i2;
	DIRECTION d;
	...
	f1 := i1 + APPLE;	/* f1 is the i1'th FRUIT */
	i2 := f2 - APPLE;	/* i1 is the index of f2 */
	d := (d - NORTH + 1) % 4 + NORTH;	/* turn clockwise */
	d := (d - NORTH + 5) % 4 + NORTH;	/* turn counter-clockwise */

We don't even have to specify that the first value is represented as 0, but
that would seem to be the most efficient. As an experiment, I treated type
'char' as an enumeration with a funny syntax for it's constants. It has
worked out quite well.

			Chris Gray   ..alberta!myrias!cg



More information about the Comp.lang.c mailing list