Ch3.6: break

The break Statement

A break statement immediately stops the nearest loop and continues execution after the loop.


break;

break only exits one loop — the innermost one.

break in a while Loop

This loop stops early when i == 50.


::std::uint_least32_t i{};
::std::uint_least32_t sum{};

while (i != 100) {
    if (i == 50) {
        break;   // exit the loop
    }
    sum = sum + i;
    ++i;
}

println("sum of [0,50) = ", sum);

break in a for Loop

break works the same way in a for loop.


::std::uint_least32_t sum{};

for (::std::uint_least32_t i{}; i != 100; ++i) {
    if (i == 10) {
        break;
    }
    sum = sum + i;
}

println("sum of [0,10) = ", sum);

break in Dead Loops

A dead loop runs forever unless something inside it stops the loop.


::std::uint_least32_t i{};

for (;;) {   // infinite loop
    if (i == 5) {
        break;   // exit the loop
    }
    println("i=", i);
    ++i;
}

This loop ends only because of break.

break with Init-statement Loops

break works normally even when the loop uses an init-statement.


for (auto i = 0; i < 100; ++i) {
    if (i == 3) {
        break;
    }
    println("i=", i);
}

Nested Loops

break only exits the innermost loop.


for (::std::uint_least32_t i{}; i != 3; ++i) {
    for (::std::uint_least32_t j{}; j != 3; ++j) {
        if (j == 1) {
            break;   // exits only the inner loop
        }
        println("i=", i, ", j=", j);
    }
}

Future Proposal: Labeled break (P3568)

The C++ committee is discussing a proposal (P3568) that would add labeled break to the language. This feature is not part of C++ yet, but it may appear in a future standard.

The idea is to allow break to exit an outer loop directly. The label must appear before the loop you want to break.

Example (proposed syntax)


outer:
for (::std::uint_least32_t i{}; i != 3; ++i) {
    for (::std::uint_least32_t j{}; j != 3; ++j) {
        if (j == 1) {
            break outer;   // exits the loop labeled "outer"
        }
        println("i=", i, ", j=", j);
    }
}

The label must be placed before the loop header. You cannot put the label after the loop or after the for keyword.

Again, this is not valid C++ today. It is shown only to illustrate how break may evolve in the future.

Pseudo-graph: Where break Goes


          ┌───────────────┐
          │     loop       │
          │    begins      │
          └───────┬───────┘
                  │
                  ▼
          ┌───────────────┐
          │     cond       │─── false ───▶ loop ends
          └───────┬───────┘
                  │ true
                  ▼
          ┌───────────────┐
          │     body       │
          └───────┬───────┘
                  │
                  ├──▶ if (break) ───────────────▶ loop ends
                  │
                  ▼
          ┌───────────────┐
          │      step      │
          └───────┬───────┘
                  │
                  └─────────────── back to cond
      

Key takeaways