tags:

views:

1658

answers:

7

Hi, I was wondering in C++ if I have an enum can I access the value at the second index? For example I have

enum Test{hi, bye};

if I want 'hi', can I do something like Test[0], thanks.

+1  A: 

No. But if you give a use-case, there might be good alternatives.

A: 

Enumerations map names to values. In your case, (int)hi would have a value of 0, and (int)bye a value of 1. You can use a cast to get the value of hi:

int myInteger = 0;
Test myValue = (Test)myInteger;

Note, though, that myValue could be an invalid enum value if myInteger is out of range.

strager
A: 

No, but you could cast from int

Test test = (Test)0;
Rob Prouse
+1  A: 

Your best option might be something like this:

enum Test{hi = 0, bye};

Then you can simply refer to 'hi' with the number 0, and 'bye' with 1.

Although this really defeats the whole purpose of using an enumeration in the first place.

Andrew
+5  A: 

Yes and no. If your Enum does not have explicit values then it is possible. Without an explicit values, enum values are given numeric values 0-N in order of declaration. For example ...

enum Test {
  hi, // 0
  bye // 1
}

This means that indexes just translates into a literal value.

Test EnumOfIndex(int i) { return static_cast<Test>(i); }

This of course does 0 validation at runtime and as soon as you add an explicit value it will break down. But it will work in the default scenario.

JaredPar
static_cast<Test>(i)!!
Martin York
Added :). I didn't know offhand when I wrote the sample if static_cast was legal so i omitted it. Haven't been near a C++ compiler since I wrote it. Thanks for the update.
JaredPar
+3  A: 

Unless specified otherwise, enums start numbering at 0, and increment by 1 each entry.

enum Test
{
    hi, //0
    bye, //1
    count //2
}

You can cast an int to the type of the enum to get the value you want, such as:

(Test)0;
//or
Test(0);

Which lets you do things like:

for(int i = 0; i < count; i++)
{
    DoSomething((Test)i);
}
xan
Use static_cast<Test>(i) instead of (Test)i
jab
+1  A: 

Depends what you mean by "I want 'hi'".

If you mean you want the value, then you can get it by casting an int, as others have said.

Casting a numeric literal to enum type is usually pointless - if you know which value you're expecting, you can use the name. That way, the enum can change without breaking your code. I guess it's possible that something really weird is going on, where someone has created an enum, and documented what "3" means but not which enum value it is. But then you'd want to fix the API.

Casting an integer value known at runtime to enum might be helpful if you have serialized data. As long as you know it's in range of the enum, the result is defined.

If you mean you want the string "hi", then you can't have it. Unlike Java, in C++ the names of the values in enumerated types exist only at compile time, not at runtime, and only map in one direction.

Steve Jessop