Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 171 ยท Control Flow

break, continue and goto

Learn how break and continue control C++ loops, how to exit nested loops cleanly with functions, flags and lambdas, and why goto is almost never the answer.

Most loops run until their condition becomes false. Real programs are messier: you find what you were searching for halfway through, you meet a line of input you want to ignore, or the user types "quit". C++ gives you three jump statements for these moments: break leaves a loop early, continue skips to the next iteration, and goto jumps to a label anywhere in the function.

The first two are everyday tools. The third is mostly a piece of history that you need to recognize, not use. In this lesson you'll learn exactly what each one does, the classic traps (a break inside a switch, a continue that skips the increment), and the clean ways to escape from nested loops, which is the one problem break can't solve on its own.

break: leave the loop now

break immediately ends the innermost enclosing for, while, do-while or switch. Execution continues with the first statement after that loop. Anything left in the loop body is skipped, and the loop condition is not checked again.

The most common use is a search: once you've found what you need, there is no point in looking at the rest.

C++ Stop at the first match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Days 4, 5 and 6 are never examined: the loop ends at day 3. Notice the -1 "not found" marker. Searches like this are so common that the standard library has them built in. std::ranges::find_if(temperatures, [](int t) { return t > 30; }) does the same job in one line. You'll meet it in Algorithms: Searching, Sorting and Counting; until then, a loop with break is perfectly fine.

The loop-and-a-half

Sometimes the natural exit point is in the middle of the loop body: you must read something before you know whether to stop. Writing while (true) with a break at the right spot expresses that directly:

C++ Read until a sentinel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The Input box is preset with three items, the word done and one extra line, so that last line is never read. Try deleting done from the Input box: the loop then ends because std::getline fails at the end of input. (Reading input in loops is covered in Reading User Input and while and do-while Loops.)

A while (true) loop is fine as long as every way out is easy to see. If a loop has five breaks scattered through forty lines, readers can't tell when it ends. At that point, move the body into a function or rethink the condition.

continue: skip to the next iteration

continue abandons the current iteration of the innermost loop and jumps to the point where the loop decides whether to go again:

  • In a while or do-while, that is the condition.
  • In a classic for, it is the increment expression (++i), then the condition.
  • In a range-based for, it moves to the next element.

Use it to filter out items you don't want to process, so the main logic doesn't have to be nested inside an if:

C++ Skip comments and bad values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The program prints the warning for line 4 and a total of 445 cents. Each continue is a guard clause: it handles a special case and gets out of the way, so the code that does the real work stays at the left margin.

Notice that ++line_number comes before any continue. That placement matters, as the next section shows.

The skipped-increment trap

In a for loop, continue still runs the increment, because the increment belongs to the loop header. In a while loop, the "increment" is just an ordinary statement in the body, and continue jumps right over it:

C++
int i = 0;
while (i < 10) {
    if (i % 2 == 0) {
        continue;    // BUG: ++i below never runs, so i stays 0 forever
    }
    std::println("{}", i);
    ++i;
}

This loop never ends. The fixes are to increment before the continue, or better, to write it as a for loop, where the loop variable's update can't be skipped:

C++
for (int i = 0; i < 10; ++i) {
    if (i % 2 == 0) {
        continue;    // ++i still runs
    }
    std::println("{}", i);    // 1 3 5 7 9
}

break and continue inside a switch

switch statements use break too (see switch Statements), and this is where the "innermost" rule bites. When a switch sits inside a loop, a break inside the switch leaves only the switch, not the loop. continue, on the other hand, ignores switch completely and applies to the loop.

C++ A command loop with a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The final + in the Input box is never processed, because q sets running to false. The unknown command ? prints its message, and its continue skips the "volume" line. If you change the q case to just break;, the program keeps reading and ends with volume 7 instead of 6.

To leave a loop from inside a switch, use a flag like running above, or put the loop in a function and return. Some code uses goto for this; the next sections explain why the alternatives read better.

Breaking out of nested loops

break exits one level only. In a nested loop, the inner break lands you in the outer loop, which happily carries on. C++ has no labeled break like Java or JavaScript (break outer;), so you need another plan. There are three good ones:

  1. A flag variable that the outer loop checks.
  2. A function containing the loops, which returns as soon as it's done. This is usually the cleanest.
  3. An immediately invoked lambda: the same idea as a function, written in place.

Here are all three, searching a cinema seating plan for the first free seat (0):

C++ Three ways out of nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

All three find row 1, seat 2, and none of them ever looks at row 2. Compare them:

  • The flag works anywhere but spreads the exit logic over two places, and forgetting the && !found check is an easy mistake.
  • The function gives the search a name, makes it reusable and testable, and return exits every loop at once. std::optional (from Returning Values) lets it say "nothing found" without a magic -1.
  • The lambda is handy when the search is used once and needs many local variables; the [&] captures them by reference. The () right after the closing brace calls it immediately. Lambdas get their own lesson in Lambda Expressions.

goto: jumping to a label

goto label; transfers control to a statement marked label: somewhere in the same function. Labels have function scope, so you can jump forward or backward, into or out of blocks, subject to a few rules. It does solve the nested-loop problem in one line:

C++ goto out of three loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

It prints found: 5 12 13 and search finished; the "no triple found" line is jumped over. It works, so why does nearly every style guide discourage goto?

  • Readers can't see the structure. A loop, an if or a return tells you its shape at a glance. A goto can go anywhere in the function, so you have to find the label and reason about every path that reaches it. Code with many gotos turns into "spaghetti".
  • It doesn't name the idea. first_free_seat(seats) explains what happens; goto done only says where to go next.
  • Better tools exist. Every classic use of goto has a structured replacement in C++, as the list below shows.

The compiler also enforces rules that make goto awkward. You can't jump forward over the initialization of a variable that is still in scope at the label, because that variable would exist without ever having been initialized:

C++
int main() {
    goto skip;
    int x = 5;
skip:
    std::println("{}", x);
}

GCC rejects this with error: jump to label 'skip' and the note crosses initialization of 'int x'. You also can't jump into a try block or a catch handler. Jumping backward or out of a block is allowed; local objects whose scope you leave are destroyed properly, just as with break.

What goto was used for, and what replaced it

Old goto use Modern C++ replacement
Exiting nested loops A function with return, or a lambda
Jumping to shared cleanup code at the end of a function (common in C) RAII: destructors clean up automatically on every exit path (Destructors and RAII)
Retrying an operation A while or do-while loop
Jumping to error handling Early return, exceptions, or std::expected (Exceptions)

You'll still see goto in C code, in some low-level C++ (state machines in parsers, generated code), and occasionally for the nested-loop exit when a function would be awkward. Recognize it, understand it, and reach for it only when the alternatives are clearly worse, which in C++ is rare.

Since C++23, a label may appear at the very end of a block, right before the closing brace, as C allows. Older standards required a statement after every label, so you'll see label: ; (a label on an empty statement) in older code.

Writing loops that rarely need jumps

break and continue are not bad style. A search loop with one break, or a filter with a couple of guard-clause continues, is clear and idiomatic. A few habits keep them that way:

  • Put the main exit in the condition when you can. while (!done && has_more_input) is easier to read than a while (true) with exits hidden inside.
  • Keep loop bodies short. If you need a break from deep inside a long body, the body probably wants to be a function.
  • Prefer for over while when there's a counter, so continue can't skip the update.
  • Let algorithms do the searching. std::ranges::find, find_if, any_of and friends replace most "loop until found, then break" code, as you'll see in the STL chapter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? for (int i = 0; i < 5; ++i) { if (i == 3) break; std::print("{} ", i); }

    When i reaches 3, break ends the loop before the print runs, so only 0, 1 and 2 are printed.
  2. 2. What does this print? for (int i = 0; i < 6; ++i) { if (i % 2 == 0) continue; std::print("{} ", i); }

    continue skips the print for even numbers, but in a for loop the increment ++i still runs, so the loop moves on and prints the odd numbers.
  3. 3. A switch is inside a while loop. What does a break inside one of the cases do?

    break exits the innermost enclosing switch or loop, which here is the switch. To stop the loop, use a flag or return from a function.
  4. 4. You need to stop two nested loops as soon as a match is found. Which approach is usually the cleanest in modern C++?

    A function names the search and return leaves every loop at once. C++ has no multi-level break, and exceptions are for errors, not normal control flow.
  5. 5. Why does the compiler reject a goto that jumps forward past int x = 5; to a label where x is still in scope?

    Jumping over an initialization into the variable's scope would create a variable that was never initialized, so C++ makes it an error ("crosses initialization").

Summary

  • break ends the innermost loop or switch immediately; execution continues after it.
  • continue skips the rest of the current iteration. In a for loop the increment still runs; in a while loop, a continue can skip your manual increment and loop forever.
  • Inside a switch in a loop, break leaves only the switch, while continue applies to the loop.
  • C++ has no labeled break. To leave nested loops, use a flag, a function with return (usually best), or an immediately invoked lambda.
  • goto jumps to a label in the same function. It can't skip over initializations, it hides structure, and RAII, functions, loops and exceptions replace all its classic uses.

Next: C-Style Arrays, where you'll store many values under one name and learn why modern C++ usually reaches for std::array and std::vector instead.