6

Possible Duplicate:
looping through enum values

Suppose we're dealing with a deck of cards

typedef enum {
    HEARTS, CLUBS, DIAMONDS, SPADES, SUIT_NOT_DEFINED
} Suit;

How can i enumerate over an enum?

Community
  • 1
  • 1
James Raitsev
  • 87,465
  • 141
  • 322
  • 462

1 Answers1

6

You can use the lower bound of the enum as the starting point and test that against the upper bound in the loop condition:

for(int i = HEARTS; i < SUIT_NOT_DEFINED; ++i) {
   //do something with i...
}
Jacob Relkin
  • 156,685
  • 31
  • 339
  • 316
  • 1
    Well, if SUIT_NOT_DEFINED wasn't defined, then he could still iterate as such: `for (int i=HEARTS;i<=SPADES;++i) {...}` since he isn't using a enumeration type for the loop invariant variable. – gschandler Dec 06 '11 at 04:09