Access an enum using an index in C

后端 未结 4 1516
梦毁少年i
梦毁少年i 2021-01-13 09:17

Consider:

enum Test
{
    a = 3,
    b = 7,
    c = 1
};

I want to access the enum using an index. Something like this:

for         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-13 09:27

    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.

提交回复
热议问题