Lesson 98 +10 XP

Using Enum Flags

Using Enums for Flags

Enums are great for small sets of options and "state" values in real programs.

Setting status

enum GameState {
    MENU,
    PLAYING,
    PAUSED,
    GAME_OVER
};

enum GameState state = MENU;

Comparing enums

if (state == PLAYING) {
    printf("Run the game!");
}

Enum in a switch

switch (state) {
    case MENU: printf("Show menu"); break;
    case PLAYING: printf("Play!"); break;
    default: printf("Paused or over.");
}

TL;DR

  • Use enums for small fixed sets of states.
  • Compare enum values directly with ==.
  • Switch + enum is a clean state machine.
  • Names make the intent obvious.