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

Using break to exit infinite loops on condition

Using break to exit infinite loops on condition

What you'll learn: How to use the break keyword to stop a loop the moment a specific event occurs.

The Emergency Exit

Imagine you are filling a bucket with water. You have a general plan to keep pouring, but you have one strict rule: if the water reaches the rim, you stop immediately. In C programming, an infinite loop is like that continuous pour, and the break statement is your emergency stop button.

While we usually give loops a condition to check at the very start (like while (x < 10)), sometimes we don't know exactly when a loop should end until we are halfway through the code inside it. By using break, you can exit a loop at any time, from any line, regardless of what the main loop condition says.

Building a "Manual" Stop

We often create an infinite loop using while (1). Since 1 is always true in C, this loop would theoretically run forever. To prevent your program from freezing or running until the end of time, you place an if statement inside the loop. When that if condition becomes true, the break command executes, and the program instantly jumps to the code following the loop's closing brace.

#include <stdio.h>

int main() {
    int cookiesEaten = 0;

    // A loop that wants to run forever
    while (1) {
        cookiesEaten++;
        printf("You have eaten %d cookie(s).\n", cookiesEaten);

        // Our "emergency exit" condition
        if (cookiesEaten == 5) {
            printf("Wait! The jar is empty. Stopping now.\n");
            break; // This exits the while loop immediately
        }
    }

    printf("Back to your daily routine.\n");
    return 0;
}

Why use this?

This pattern is incredibly useful for user input. For example, you might want to keep asking a user for numbers until they type 0 to quit. Instead of trying to force a complex condition into the while(...) parenthesis, you can run a simple while (1) and put a break right after the line where you read the user's input. It makes your code read like a conversation: "Do this forever, but if this happens, stop."

Key takeaway

The break statement provides an immediate exit from a loop, allowing you to stop an infinite process as soon as a specific condition is met.