Break/Continue

Break/Continue in C++: Imagine queueing to check every book on a shelf. is walking out of the library.

The Analogy: Leaving the Queue

Imagine queueing to check every book on a shelf.

break is walking out of the library. You found what you needed — or realised something is badly wrong — and the whole search stops immediately. Nothing after you on the shelf gets looked at.

continue is skipping the book in your hands and reaching for the next one. You are still in the library, still working through the shelf; this particular book just did not qualify.

Both are jumps. Used sparingly they make a loop clearer by letting the main body assume the easy case. Used carelessly they scatter the exit points of a loop across thirty lines and make the code very hard to follow.


Syntax or Core Structure

#include <iostream>
#include <string>
#include <vector>

int main() {
    // break: stop the loop entirely
    const std::vector<std::string> names{"Ada", "Alan", "Grace", "Edsger"};
    const std::string target{"Grace"};

    for (std::size_t i = 0; i < names.size(); ++i) {
        if (names[i] == target) {
            std::cout << "Found at index " << i << "\n";
            break;                          // Edsger is never checked
        }
    }

    // continue: skip the rest of THIS pass, go to the next
    for (int i = 1; i <= 10; ++i) {
        if (i % 2 != 0) {
            continue;                       // odd -- skip the printing
        }
        std::cout << i << " ";              // 2 4 6 8 10
    }
    std::cout << "\n";

    // break in a while
    int n{0};
    while (true) {
        if (n >= 3) { break; }              // the only way out
        std::cout << n++ << " ";
    }
    std::cout << "\n";

    return 0;
}

Both keywords affect the innermost enclosing loop only. break also ends a switch, which is why a break intended for a loop but written inside a switch silently does the wrong thing.


Technical Depth: Nesting, Skipped Updates and the switch Collision

They only escape one level

for (int row = 0; row < 3; ++row) {
    for (int col = 0; col < 3; ++col) {
        if (grid[row][col] == target) {
            break;               // leaves the COLUMN loop only -- rows continue
        }
    }
}

There is no break 2 in C++. Three ways to leave both loops:

// 1. A flag -- explicit, slightly verbose
bool found{false};
for (int row = 0; row < 3 && !found; ++row) {
    for (int col = 0; col < 3; ++col) {
        if (grid[row][col] == target) { found = true; break; }
    }
}

// 2. Extract a function and return -- usually the cleanest
bool contains(const Grid& g, int target) {
    for (int row = 0; row < 3; ++row) {
        for (int col = 0; col < 3; ++col) {
            if (g[row][col] == target) { return true; }   // leaves everything
        }
    }
    return false;
}

// 3. goto -- legal, and the one case where it is defensible
for (int row = 0; row < 3; ++row) {
    for (int col = 0; col < 3; ++col) {
        if (grid[row][col] == target) { goto done; }
    }
}
done:

Option two is the right answer almost every time. A nested search that wants to escape both loops is telling you it deserves to be its own function.

continue in a while can hang your program

// INFINITE LOOP
int i{0};
while (i < 10) {
    if (i % 2 == 0) {
        continue;       // jumps to the condition -- ++i is NEVER reached
    }
    std::cout << i;
    ++i;
}

// A for loop is safe: the update is part of the header
for (int i = 0; i < 10; ++i) {
    if (i % 2 == 0) { continue; }   // ++i still runs
    std::cout << i;
}

In a for loop, continue jumps to the update and then the condition. In a while or do-while it jumps straight to the condition, skipping anything below it in the body — including your increment. This is the single most important difference between the two, and it is why for is safer when continue is involved.

break and switch interfere

while (running) {
    switch (command) {
        case 'q':
            break;          // ends the SWITCH, not the while. The loop continues!
    }
}

// Fix: set a flag, or return
while (running) {
    switch (command) {
        case 'q':
            running = false;
            break;          // ends the switch; the while condition now stops it
    }
}

A break inside a switch inside a loop always belongs to the switch. There is no syntax to reach past it, so use a flag or extract the loop into a function and return.

The guard-clause style

// Nested: the real work drifts rightwards
for (const Order& o : orders) {
    if (o.isValid()) {
        if (!o.isCancelled()) {
            if (o.total > 0) {
                process(o);
            }
        }
    }
}

// continue as a guard: flat, and each rejection can be logged
for (const Order& o : orders) {
    if (!o.isValid())   { ++invalidCount; continue; }
    if (o.isCancelled()){ ++cancelled;    continue; }
    if (o.total <= 0)   { ++empty;        continue; }

    process(o);
}

This is continue at its best: filtering conditions listed at the top, each with its own handling, and the body left to do one job. It is the loop equivalent of an early return.

What each one does

breakcontinuereturn
Leavesthe innermost loop or switchthe current pass onlythe whole function
Loop keeps runningnoyesno
In a for, runs the updatenoyesno
In a while, runs code below itnonono
Escapes nested loopsnonoyes

Real World Example: Validating a Batch of Records

#include <iostream>
#include <string>
#include <vector>

struct Record {
    std::string id;
    std::string email;
    int age;
    double amount;
};

int main() {
    const std::vector<Record> batch{
        {"R001", "ada@example.com",  36,  120.00},
        {"R002", "",                 22,   45.00},   // no email -- skip
        {"R003", "alan@example.com", -5,   80.00},   // bad age -- skip
        {"R004", "grace@example.com",41,    0.00},   // zero amount -- skip
        {"R005", "edsger@example.com",39, 250.00},
        {"CORRUPT", "", 0, -1.0},                    // sentinel -- stop entirely
        {"R006", "linus@example.com", 30, 999.00},   // never reached
    };

    double total{0.0};
    int accepted{0}, skipped{0};

    for (const Record& r : batch) {
        // A fatal condition ends the whole batch
        if (r.amount < 0.0) {
            std::cout << "! Corrupt record " << r.id << " -- aborting batch\n";
            break;
        }

        // Guard clauses: each rejection is reported and skipped
        if (r.email.empty()) {
            std::cout << "- " << r.id << ": missing email\n";
            ++skipped;
            continue;
        }
        if (r.age < 18 || r.age > 120) {
            std::cout << "- " << r.id << ": implausible age " << r.age << "\n";
            ++skipped;
            continue;
        }
        if (r.amount == 0.0) {
            std::cout << "- " << r.id << ": nothing to charge\n";
            ++skipped;
            continue;
        }

        // By here the record is known good -- one clear job
        total += r.amount;
        ++accepted;
        std::cout << "+ " << r.id << ": " << r.amount << "\n";
    }

    std::cout << "\nAccepted " << accepted << ", skipped " << skipped
              << ", total " << total << "\n";
    return 0;
}

The two keywords express two genuinely different decisions. A negative amount means the data itself cannot be trusted, so break stops the batch rather than processing possibly-garbled records after it. The three validation failures are per-record problems, so continue skips just that one and keeps going — and because each guard sits at the top with its own message, the reason for every rejection ends up in the log. The final block has no nesting at all: once execution reaches it, the record is valid by construction.


Common Mistakes

  • continue in a while before the increment. Infinite loop. Move the increment above it or use for.
  • Expecting break to escape two loops. It leaves one level. Extract a function and return.
  • break inside a switch inside a loop. It ends the switch; the loop carries on.
  • Using break where the loop condition should say it. while (true) { if (done) break; } often reads better as while (!done).
  • Code after break or continue in the same block — unreachable, and some compilers warn.
  • Overusing continue until a loop has six exit paths. Past three or four, extract a predicate function.
  • Forgetting that break skips the for update, so the counter holds the value it had when you left.

Best Practices

  1. Use continue as a guard clause at the top of the body to flatten nesting.
  2. Prefer return from an extracted function over flags and goto for escaping nested loops.
  3. Put the condition in the loop header when you can. while (!found && i < n) documents the exit; a buried break does not.
  4. Set a flag when you need to leave a loop from inside a switch.
  5. Reach for the standard algorithms. std::find_if and std::any_of express "search and stop" without a manual break.
  6. Keep every break and continue visible near the top of the body, not buried thirty lines down.

Practice Exercises

  1. First negative: Given a std::vector<int>, print the index of the first negative value using break, then rewrite it with std::find_if and compare the two.
  2. Skip the blanks: Read lines with std::getline and print each one numbered, using continue to skip blank lines and lines starting with # — and keep the numbering counting only the lines you printed.
  3. Escape both loops: Write a function that searches a 5x5 grid for a value and returns its row and column. Solve it with return, then again with a boolean flag, and write one sentence on which you find easier to read.