Access an enum using an index in C

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

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?

回答1:

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.



回答2:

Your question demonstrates you don't really understand what an enum is for.

It is not something that can be indexed, nor is there ever any reason to. What you have defined is actually just 3 constants named a, b, and c, whose values are 3, 7, and 1 respectively.



回答3:

You can't do that. A C enum is not much more than a bunch of constants. There's no type-safety or reflection that you might get in a C# or Java enum.



回答4:

As someone else mentioned, this is not the purpose of an enum. In order to do what you are asking, you can simply use an array:

#define a 3 #define b 7 #define c 1  int array[3] = { a, b, c }; int i;  for( i = 0; i < sizeof(array)/sizeof(array[0]); i++ ) {     doSomething( array[i] ); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!