开发者

Cycle every item in an enum

Is it possible to cycle and extract its va开发者_运维百科lue for every item in an enum, e.g:

enum {
   item 1 = 1,
   item 2 = 7,
   item 3 = 'B'
} items;

To say, an array. Possible?


Do you mean to construct an array with one element for each value of the enum? Such that you would end up with an array {1, 7, 'B'}?

Not possible. An enum is not much more than a bunch of compile-time constants. At runtime, they are effectively just ints. The compiler doesn't even check to make sure you are putting valid values in your enum variable (you could put the value 5 in there and it wouldn't mind). So it has no knowledge of what the possible enum values are at runtime.

Of course, if your enum is contiguous (say, you had defined an enum for the values 0, 1, 2 and 3), then you can do this using a for loop.


it's not possible. enum items are simply constants, an analogy could be #defined constants:

#define item_1 1
#define item_2 7
#define item_3 'B'

(Warning, #define and enum aren't equal. This is just an analogy).


This is not possible in the manner that you expect. Assuming you assign sequential numbers to the members of an enum, then you can iterate over the values using a loop. Unfortunately, this is the best you can do. See this answer for a more in-depth explanation.


You could give your enum items explicitly contiguous values such as:

enum {
   item1=0,
   item2=1,
   numberOfItems=2
} myEnum;

and then cycle as

for (k=item1; k<=numberOfItems; k++)

but it is of course up to you to make sure that myEnum is contiguous (i.e. contains the values you try to cycle in this way).


If you need to do this in a real application, which is a quite common scenario, you would do it in the following manner:

#define ITEM_N  3

typedef enum
{
  item1 = 1,
  item2 = 7,
  item3 = 'B',
} Item_t;

const Item_t LOOKUP_TABLE [ITEM_N] =
{
  item1,
  item2,
  item3
};

...

for(i=0; i<ITEM_N; i++)
{
  printf("%d\n", LOOKUP_TABLE[i]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜