looping through enum values

Given

enum Foo {Bar=0,Baz,...,Last};

you can iterate the elements like:

for(int i=Bar; i<=Last; i++) {
  ...
}

Note that this exposes the really-just-an-int nature of a C enum. In particular, you can see that a C enum doesn’t really provide type safety, as you can use an int in place of an enum value and vice versa. In addition, this depends on the declaration order of the enum values: fragile to say the least. In addition, please see Chuck’s comment; if the enum items are non-contiguous (e.g. because you specified explicit, non-sequential values for some items), this won’t work at all. Yikes.

Leave a Comment