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

Using enums for state machines

Using enums for state machines

What you'll learn: How to use enumerations to manage the logical flow of a program by defining clear, readable states.

The logic of a traffic light

Imagine you are writing code for a microwave. At any given moment, the microwave is doing exactly one thing: it’s either IDLE, HEATING, or PAUSED. In C, you could represent these states using integers (0, 1, and 2), but your code would quickly become a confusing mess of magic numbers. If you see if (status == 2), you have to hunt through your notes to remember what "2" means.

This is where enums shine. An enum allows you to give human-readable names to these integer values, making your code act like a "state machine." A state machine is just a system that moves from one labeled state to another based on inputs.

Building the state machine

By combining an enum with a switch statement, you create a robust structure for your program’s logic. The enum defines the possibilities, and the switch handles the transitions.

#include <stdio.h>

// Define the possible states for a simple game player
enum PlayerState {
    STANDING,
    RUNNING,
    JUMPING,
    FALLING
};

int main() {
    // Start the player in the STANDING state
    enum PlayerState currentPlayer = STANDING;

    // A simple simulation of state logic
    switch (currentPlayer) {
        case STANDING:
            printf("Player is still. Press 'W' to run.\n");
            currentPlayer = RUNNING; // Transition to a new state
            break;
        case RUNNING:
            printf("Player is moving fast!\n");
            break;
        case JUMPING:
            printf("Player is in the air!\n");
            break;
        case FALLING:
            printf("Player is descending.\n");
            break;
    }

    return 0;
}

Why this matters

Using enums for states provides two major benefits:

  1. Readability: case RUNNING is instantly understandable, whereas case 1 is not. This makes your code self-documenting.
  2. Safety: If you use a switch statement with an enum, many modern compilers will warn you if you forget to handle one of the states. This prevents bugs where a program enters a state (like FALLING) but has no instructions on what to do next.

State machines are the backbone of game development, robotics, and embedded systems. Using enums ensures that your logic remains organized as your projects grow in complexity.

Key takeaway

Enums turn abstract numbers into meaningful labels, allowing you to create readable state machines that control program flow with clarity and safety.