user1128265 user1128265 - 2 months ago 7
C Question

Access an enum using an index in C

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?

Answer

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.

Comments