enums

Tom Karzes karzes at mfci.UUCP
Wed Jul 20 18:00:41 AEST 1988


While on the subject of enums, here's something that's always bothered me.
If you define an enum with a long list of values, a natural thing to want
to do is determine the number of values in the enum (sort of like sizeof).

For example:

    enum tree {
        oak,
        elm,
        maple,
        birch,
        willow,
        cypress,
        spruce
    };

Now I'd like to define TREE_COUNT to be the number of trees.  So I have to
painfully count them, and write:

    #define TREE_COUNT 7

and hope that people correctly update this macro every time they add or
delete a tree.

Sure, I suppose in this case I could write:

    #define TREE_COUNT ((int) spruce + 1)

(This assumes that there aren't any trees which have been given explicit
values in the enum.)  But this is still a pain to maintain, since you
have to fix the macro every time the last tree changes.

Of course, in the presence of enum members which are given explicit values
(which also introduces the possibility of duplicate values), you may want
to know something more than just the number of members (e.g., the number
of distinct values, the minimum and maximum values, etc.).  However, for
most situations it would be sufficient to simply know the number of members
in the enum.

Does ANSI C provide a reasonable way to do this?



More information about the Comp.lang.c mailing list