Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access an enum using an index in C

Tags:

c

enums

indexing

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?

like image 263
user1128265 Avatar asked Apr 19 '12 16:04

user1128265


People also ask

Can you access enum by index?

Use the Object. values() method to get an array containing the enum's values. Use square brackets to access the array at the specific index and get the value.

Can you index array in enum?

Enum, array indexes. An enum array has many uses. It can be accessed with enum values. This example shows how to index an array of values with enum keys.

Can you cast an enum in C?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.

Can we assign value to enum in C?

We can also provide the values to the enum name in any order, and the unassigned names will get the default value as the previous one plus one. The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc.


1 Answers

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.

like image 160
zwol Avatar answered Oct 18 '22 21:10

zwol