Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over an enum?

Tags:

c++

enums

I just noticed that you can not use standard math operators on an enum such as ++ or +=

So what is the best way to iterate through all of the values in a C++ enum?

like image 517
Adam Avatar asked Nov 04 '08 13:11

Adam


People also ask

Can you iterate through an enum in C?

you can iterate the elements like: for(int i=Bar; i<=Last; i++) { ... } Note that this exposes the really-just-an-int nature of a C enum. In particular, you can see that a C enum doesn't really provide type safety, as you can use an int in place of an enum value and vice versa.

How do I iterate enum in VB?

To iterate through an enumeration, you can move it into an array using the GetValues method. You could also iterate through an enumeration using a For... Each statement, using the GetNames or GetValues method to extract the string or numeric value.

How do I get all the enum values in typescript?

To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) . The Object.


1 Answers

The typical way is as follows:

enum Foo {   One,   Two,   Three,   Last };  for ( int fooInt = One; fooInt != Last; fooInt++ ) {    Foo foo = static_cast<Foo>(fooInt);    // ... } 

Please note, the enum Last is meant to be skipped by the iteration. Utilizing this "fake" Last enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum. If you want to add more enums later, just add them before Last. The loop in this example will still work.

Of course, this breaks down if the enum values are specified:

enum Foo {   One = 1,   Two = 9,   Three = 4,   Last }; 

This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.

switch ( foo ) {     case One:         // ..         break;     case Two:  // intentional fall-through     case Three:         // ..         break;     case Four:         // ..         break;      default:         assert( ! "Invalid Foo enum value" );         break; } 

If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.

like image 97
andreas buykx Avatar answered Sep 21 '22 17:09

andreas buykx