Course contentsShow
← C
Lesson 261 of 1,2194. Control FlowFree lesson

Fall-through behavior: intentional and accidental

Fall-through behavior: intentional and accidental

What you'll learn: You will understand how C execution moves between switch cases and how to use the "fall-through" effect to group multiple conditions together.

The Missing Stop Sign

In most programming logic, we expect a match to happen, code to run, and the program to move on. However, the switch statement in C is different. It acts more like a high-speed train track. Once the program finds a case that matches, it jumps onto the track and keeps rolling downward through every subsequent case until it hits a break; statement.

If you forget the break;, the program "falls through" into the next case's code, even if that case's value doesn't match your variable!

Intentional Fall-through

Sometimes, this behavior is a superpower. Imagine you are building a simple game menu. You want the same logic to trigger whether the user types a lowercase 'q' or an uppercase 'Q'. Instead of writing the same code twice, you can stack the cases.

#include <stdio.h>

int main() {
    char command = 'q';

    switch (command) {
        case 'Q': // No break here!
        case 'q':
            printf("Quitting the game...\n");
            break;
        case 's':
            printf("Starting game...\n");
            break;
        default:
            printf("Invalid command.\n");
    }
    return 0;
}

In the example above, if command is 'Q', the program enters at the first case. Since there is no code or break there, it "falls through" into the 'q' case and executes the print statement. This is a clean way to handle multiple inputs that require the same result.

The Accidental Trap

Accidental fall-through is a common source of bugs. If you intended for each case to be unique but forgot a break;, your program will execute the correct logic and then immediately execute the logic for the next case below it.

Always treat the break; like a stop sign. If you intentionally leave it out to group cases, it is a good habit to add a comment like /* fall-through */ so other programmers know it wasn't a mistake.

Key takeaway

A switch case will execute all subsequent code until it hits a break;, allowing you to group multiple cases together for a single outcome.