Course contentsShow
← C
Lesson 665 of 1,2199. Structures and UnionsFree lesson

Using enums in switch statements

Using enums in switch statements

What you'll learn: How to use the descriptive names of an enumeration to create readable and organized decision-making logic in your code.

The perfect match

In previous lessons, you learned that an enum is essentially a set of named integer constants. Because an enum maps directly to integers, it is the perfect partner for a switch statement.

Think of a switch statement as a mail sorting room. When a letter comes in, the sorter looks at the zip code and puts it into a specific bin. If you use raw numbers (like 1, 2, or 3), the sorter has to memorize what every number means. But if you use an enum, the bins are clearly labeled "Priority," "Standard," and "International." It makes the process much harder to mess up.

Readable logic

When you use an enum variable as the expression in a switch, you can use the enum’s identifiers as your case labels. This removes the need for "magic numbers"—those mysterious integers that pop up in code without explanation.

Here is how you might handle a simple state machine for a game:

#include <stdio.h>

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

int main() {
    enum GameState currentStatus = PAUSED;

    switch (currentStatus) {
        case START_MENU:
            printf("Press any key to start.\n");
            break;
        case PLAYING:
            printf("The game is running...\n");
            break;
        case PAUSED:
            printf("Game is paused. Take a breath!\n");
            break;
        case GAME_OVER:
            printf("Better luck next time.\n");
            break;
        default:
            printf("Unknown state.\n");
    }

    return 0;
}

Why this matters

Using enums in a switch statement provides two major benefits:

  1. Clarity: Anyone reading your code knows exactly what case PAUSED means. They don't have to hunt through documentation to find out that "2" represents the pause screen.
  2. Safety: Modern compilers are quite smart. If you define an enum with five values but your switch statement only handles three of them, many compilers will give you a warning. This reminds you to handle every possible scenario, preventing bugs before they happen.

Key takeaway

Combining enum with switch turns abstract numbers into human-readable labels, making your logic self-documenting and easier to maintain.