How can I iterate over an enum? [c++]


One of many approaches: When enum Just Isn't Enough: Enumeration Classes for C++.

And, if you want something more encapsulated, try this approach from James Kanze.


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?

Simplest method for iterating through contiguous enum values in C++

It is indeed safe.

This would have been undefined: MyEnum(int(NUM_ENUMS) + 1) because the value to hold (4) would be greater than what the enum can represent ([0, 3]); since you ensure that m is strictly lower than NUM_ENUMS it is safe to use MyEnum(m + 1).

On the other hand, note that you would have issues with customized enums such as:

enum OtherEnum {
    Foo = -1,
    Bar = 2,
    Baz = 8,

so it is not a generic practice.

I would advise a generated array to iterate over instead:

MyEnum const Values[] = { FOO, BAR, BLECH };

Note that it is easily generated from the definition of the enum, and also avoid polluting the interface with a nonsensical value (business-wise).

C++ enum in foreach

It is common to add elements to the enum to facilitate this:

enum Rank {
    Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King,
    RankFirst = Ace, RankLast = King
enum Suit {
    Clubs, Diamonds, Hearts, Spades,
    SuitFirst = Clubs, SuitLast = Spades

Then you can write your loops as:

for (int r = RankFirst; r <= RankLast; ++r) {
    for (int s = SuitFirst; s <= SuitLast; ++s) {
        deck.add(Card((Rank)r, (Suit)s));

No, you are wrong, there is no such operator.

To get the next one, convert your value to an int, increment it, then reinterpret_cast it back to your enum. Note that going out of bounds can eventually lead to undefined behaviour, so checks are a good idea.