Kor Sar
Kor Sar

Reputation: 51

How to get index of value in Enum in C/C++

I've searched but could not find any solution for this issue. I have an enum that does not start with "0" and other values are also not in sequence which is like,

typedef enum{
a = 8,
b = 100,
c,
d = 1,
e = 9
}numberEnum;

I want to get index of an element in enum like this;

int myIndex = getIndex(a); // myIndex = 0
int myIndex1 = getIndex(d); // myIndex1 = 3
int myIndex2 = getIndex(b); // myIndex2 = 1

int getIndex(numberEnum e)
{
    // some code here

   return index;
}

I should not use Array for this situation. Using enum is a must. Is there any way to achieve this? Thanks for your help.

Upvotes: 1

Views: 10312

Answers (3)

Clifford
Clifford

Reputation: 93476

There is no semantic meaning to "indexing an enum", it is not a data structure or array, but rather a data type, there is no order, because the size of the enum is the size of a single value - "index" has no meaning. It is line asking how to index an integer; that is all an enum is, an integer with a defined subset if valid values.

You can perhaps achieve what you want (although the reason to do so escapes me) using a const array of values and using the enum to index it:

static const int values[] = {8, 100, 101, 1, 9} ;
typedef enum { a, b, c, d, e } numberEnum ;

numberEnum myIndex = a ; // myIndex = 0
numberEnum myIndex1 = d; // myIndex1 = 3
numberEnum myIndex2 = b; // myIndex2 = 1

int myValue = values[myIndex] ;
int mValue1 = values[myIndex1] ;
int mValue2 = values[myIndex2] ;

int valueC = values[c] ;

Upvotes: 1

Mari Kotlov
Mari Kotlov

Reputation: 64

You would have to make this association manually, like this:

int getIndex(numberEnum e)
{
   switch(e)
   {
       case a:
           return 0;
       case b:
           return 1;
       default:
           return -1;
   }
}

Upvotes: 4

Nicol Bolas
Nicol Bolas

Reputation: 473447

Enumerators don't have an "index value". So that's not something you can query, nor is it something you're expected to be able to. These two enumerations are functionally equivalent:

enum alpha { first, second };
enum beta { second = 1, first = 0 };

I'm sure you could do some macro stuff to generate an array mapping from enumerator names to the order they're listed in the enumeration. But that would require wrapping the enumeration and its enumerators in macros.

Upvotes: 4

Related Questions