looping through enum values looping through enum values objective-c objective-c

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.


If you enum is defined as follows:

enum Direction {  East,  West,  North,  South};

You can loop through it this way:

for ( int direction = East; direction <= South; ++direction){   /* Do something with Direction}


It's a bit of a kludge (as is the entire concept so... eh...) but if you're going to do this multiple times, and you want to be able to deal with the possibility of non-contiguous enums, you can create a (global constant) array, and have (to use ennukiller's example) Directions directions[4] = {East, West, North, South};and then in your loop you can talk about directions[i] rather than iterating directly over the directions themselves...

As I said, it's ugly, but it's slightly less fragile I think...