# How can I iterate over an enum?

### Question

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?

1
271
6/21/2013 10:04:11 AM

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);
// ...
}
``````

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.

241
2/6/2012 7:37:45 PM

``````#include <iostream>
#include <algorithm>

namespace MyEnum
{
enum Type
{
a = 100,
b = 220,
c = -1
};

static const Type All[] = { a, b, c };
}

void fun( const MyEnum::Type e )
{
std::cout << e << std::endl;
}

int main()
{
// all
for ( const auto e : MyEnum::All )
fun( e );

// some
for ( const auto e : { MyEnum::a, MyEnum::b } )
fun( e );

// all
std::for_each( std::begin( MyEnum::All ), std::end( MyEnum::All ), fun );

return 0;
}
``````