Lesson contents

C++ — Break and early exit

break leaves the nearest enclosing loop or switch. In a range-based for loop it ends traversal before any later elements are visited.

A simple example

Stop before printing 3

  1. Start with Visit 1 through 4
  2. Do this Leave at 3
  3. Result 1 → 2
When the number reaches 3 the loop ends. The print step is skipped for 3 and 4.
lesson.cpp
#include <iostream>

int main() {
    for (int n = 1; n <= 4; n++) {
        if (n == 3) {
            break;
        }
        std::cout << (n) << '\n';
    }
}
Output
1
2
Advertisements

Stop before the first unaffordable job

Process the queue in order with a budget of 10. Stop the loop as soon as the next job would exceed the remaining budget. A range-based loop exposes the job cost directly. Updating accepted after the guard ensures that the first unaffordable job is excluded.

Credit balance: 10 → 6 → 3. Next job costs: 8 credits. Queue result: 2 jobs accepted.
Stop at the first job that will not fit

A print queue has ten credits and must serve jobs in arrival order. Jobs costing four and three leave three credits. The next job costs eight, so the queue stops before the smaller job behind it.

Run the example

Use a C++17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
lesson.cpp
#include <iostream>

int main() {
    int remaining = 10;
    int accepted = 0;
    for (int cost : {4, 3, 8, 1}) {
        if (cost > remaining) break;
        remaining -= cost;
        ++accepted;
    }
    std::cout << accepted << " accepted, " << remaining << " left\n";
    return 0;
}
Output
2 accepted, 3 left

The first two jobs cost 4 and 3, leaving 3. The next costs 8, so processing stops before the later job costing 1.

Try it yourself

Replace the cost of 8 with 3. What changes?

Check your answer

The third job exactly fits. Three jobs are accepted and the remaining budget is zero. The last job cannot run.

C++17 working draft

Related tags

  • C++
  • break
  • early exit
  • iteration