Access an enum using an index in C

c, enums, indexing

Solution

This is the best you can do:

enum Test { a = 3, b = 7, c = 1, LAST = -1 };
static const enum Test Test_map[] = { a, b, c, LAST };

for (int i = 0; Test_map[i] != LAST; i++)
    doSomething(Test_map[i]);

You have to maintain the mapping yourself.

Problem

Consider: ``` enum Test { a = 3, b = 7, c = 1 }; ``` I want to access the enum using an index. Something like this: ``` for (i=0; i<n; i++) doSomething((Test)i); ``` How can I do something like this, where I will be able to access the enum using an index, though the members of the enum have different values?

Original source