C++ Break and Continue

break and continue are control statements that change how a loop runs. break stops the loop completely, while continue skips the rest of the current repetition and moves to the next one.

These statements are useful when a loop should react to a special condition instead of always running every statement in the loop body.

Using break

The break statement exits the nearest loop immediately. After break runs, the program continues with the first statement after the loop.

This example searches for the number 4. Once the number is found, there is no reason to keep looping, so break stops the loop early.

#include <iostream>

int main(void) {
    for (int number = 1; number <= 6; number++) {
        std::cout << "Checking " << number << std::endl;

        if (number == 4) {
            std::cout << "Found 4" << std::endl;
            break;
        }
    }

    std::cout << "Done" << std::endl;

    return 0;
}

Output:

Checking 1
Checking 2
Checking 3
Checking 4
Found 4
Done

The loop begins at 1 and would normally continue through 6. When number == 4 becomes true, the program prints Found 4, runs break, and leaves the loop.

Using continue

The continue statement does not stop the whole loop. It skips the remaining statements in the current repetition and moves on to the next repetition.

This example prints only odd numbers. When the number is even, continue skips the printing statement below it.

#include <iostream>

int main(void) {
    for (int number = 1; number <= 6; number++) {
        if (number % 2 == 0) {
            continue;
        }

        std::cout << number << " is odd" << std::endl;
    }

    return 0;
}

Output:

1 is odd
3 is odd
5 is odd

When number is 2, 4, or 6, the expression number % 2 == 0 is true. The continue statement skips std::cout for those values, so only the odd numbers are printed.

In for and while Loops

break and continue can be used in for loops, while loops, and do while loops. In a for loop, continue jumps to the update expression, such as number++, and then checks the condition again. In a while loop, continue jumps back to the condition check.

Because continue skips code later in the loop body, be careful in while loops if the skipped code updates a counter. Skipping the update can accidentally create an infinite loop.

Break vs Continue

Statement What it does Common use
break Leaves the nearest loop immediately Stop searching after finding a match
continue Skips to the next loop repetition Ignore values that should not be processed

Common Mistakes

  • Using break when you only meant to skip one value.
  • Using continue before important work that must happen every repetition.
  • Forgetting that break only exits the nearest loop, not every nested loop at once.
  • Making a loop harder to read by using too many early exits.

Takeaway: use break to stop a loop early, and use continue to skip only the current repetition.