Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/5/84; site myrias.UUCP Path: utzoo!utcsri!ubc-vision!alberta!myrias!cg From: cg@myrias.UUCP (Chris Gray) Newsgroups: net.lang.c Subject: Enums Message-ID: <179@myrias.UUCP> Date: Mon, 30-Sep-85 14:21:16 EDT Article-I.D.: myrias.179 Posted: Mon Sep 30 14:21:16 1985 Date-Received: Mon, 30-Sep-85 18:43:27 EDT References: <118@mit-hector.UUCP> <2792@sun.uucp> <173@myriasa.UUCP> <57@opus.UUCP> <811@rlvd.UUCP> Organization: Myrias Research, Edmonton Lines: 39 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