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

Legitimate use case: breaking out of nested loops

Legitimate use case: breaking out of nested loops

What you'll learn: How to use the goto statement to cleanly exit multiple layers of loops when a specific condition is met.

The problem with nested loops

In C, the break keyword is your standard tool for stopping a loop early. However, break has a limitation: it only exits the innermost loop. If you are working with a loop inside a loop (or three layers deep), a single break will only kick you out one level.

Imagine you are searching a 2D grid (like a spreadsheet) for a specific value. Once you find it, you want to stop everything and move on. Using only break, you would need to set a "flag" variable, check it in the inner loop, break, then check it again in the outer loop, and break again. This makes your code cluttered and harder to read.

The clean exit

This is one of the few places where the controversial goto statement is actually the cleanest solution. By defining a label outside the entire nesting structure, you can jump straight there the moment your condition is satisfied.

Think of it like an emergency exit in a large building. Instead of walking through every single door to get to the street, you use the fire escape to bypass the hallways and exit immediately.

Example: Searching a matrix

In the code below, we want to stop all processing as soon as we find the number 7.

#include <stdio.h>

int main() {
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (matrix[i][j] == 7) {
                printf("Found 7 at row %d, col %d. Exiting...\n", i, j);
                goto found; // Jump straight to the label
            }
        }
    }

    printf("This only prints if 7 is never found.\n");

found:
    printf("Search complete.\n");
    return 0;
}

By using goto found;, we bypass the remainder of the inner loop, the remainder of the outer loop, and any code sitting between the loops and the label. It provides a direct, readable path to the "End of Search" logic without needing extra boolean flags or complex logic.

Key takeaway

Use goto to jump out of deeply nested loops to a label immediately following the loops, keeping your error-handling or exit logic simple and readable.