Alex Rivera | Logout

Enum C++ Get by Index

Asked 2008-11-26T19:09:38.780
25

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.

Edit
Report

1 Answer

17

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);
}
answered 2008-11-26T19:14:45.807

Your Answer