Search

Admin

5.8 — Break and continue

Break

Although you have already seen the break statement in the context of switch statements, it deserves a fuller treatment since it can be used with other types of loops as well. The break statement causes a do, for, switch, or while statement to terminate. This includes the for each loops included in C++11.

Breaking a switch

In the context of a switch statement, a break is typically used at the end of each case to signify the case is finished (which prevents fall-through):

Breaking a loop

In the context of a loop, a break statement can be used to cause the loop to terminate early:

This program allows the user to type up to 10 numbers, and displays the sum of all the numbers entered at the end. If the user enters 0, the break causes the loop to terminate early (before 10 numbers have been entered).

Note that break can be used to get out of an infinite loop:

Break vs return

New programmers often have trouble understanding the difference between break and return. A break statement terminates the switch or loop, and execution continues at the first statement beyond the switch or loop. A return statement terminates the entire function that the loop is within, and execution continues at point where the function was called.

Continue

The continue statement provides a convenient way to jump back to the top of a loop earlier than normal, which can be used to bypass the remainder of the loop for an iteration. Here’s an example of using continue:

This program prints all of the numbers from 0 to 19 that aren’t divisible by 4.

Be careful when using a continue statement with while or do while loops. Because these loops typically increment the loop variables in the body of the loop, using continue can cause the loop to become infinite! Consider the following program:

This program is intended to print every number between 0 and 9 except 5. But it actually prints:

0 1 2 3 4

and then goes into an infinite loop. When count is 5, the if statement evaluates to true, and the loop returns back to the top. The count variable is never incremented. Consequently, on the next pass, count is still 5, the if statement is still true, and the program continues to loop forever.

Using break and continue

Many textbooks caution readers not to use break and continue, both because it causes the execution flow to jump around and because it can make the flow of logic harder to follow. For example, a break in the middle of a complicated piece of logic could either be missed, or it may not be obvious under what conditions it should be triggered.

However, used judiciously, break and continue can help make loops more readable by keeping the number of nested blocks down and reducing the need for complicated looping logic.

For example, consider the following program:

This program uses a boolean variable to control whether the loop continues or not, as well as a nested block that only runs if the user doesn’t exit.

Here’s a version that’s easier to understand, using a break statement:

In this version, by using a single break statement, we’ve avoided the use of a boolean variable (and having to understand what both what its intended use is, and where it is set), an else statement, and a nested block.

Minimizing the number of variables used and keeping the number of nested blocks down both improve code understandability more than a break or continue harms it. For that reason, we believe judicious use of break or continue is acceptable.

5.9 -- Random number generation
Index
5.7 -- For statements

11 comments to 5.8 — Break and continue

  • Najla

    Thank you so much, that was very helpful to me.

  • DrSuse

    Considering this little snippet:

    int iii=0;
    while (iii < 10)
    {
    if (iii==5)
    continue;
    cout << iii << " ";
    iii++;
    }

    Is there any elegant way to make this work as intended as a “while” function?
    If you put the increment (iii++) before the if, then “0” never gets printed. The only way I know to get “0” included in the output this way is to initialize iii as -1, which seems like a very sloppy way to do things.
    You could replace “continue;” with an “iii++” and get the desired result, , but I would like to see how this could be done, simply and elegantly, using the “continue” statement.

    • deadLOCC3D


      int iii=0;
      while (iii < 10)
      {
      if (iii==5)
      {
      iii++;
      continue;
      }
      cout << iii << " ";
      iii++;
      }

      • Alex

        This works but is somewhat inelegant, since you have two places where the loop variable can get incremented.

        Personally, I’d use a for loop, because a for loop will always increment the loop variables even if continue is used.

        You could also invert the logic:

  • A suggestion for a useful coding style:

    When using break and/or continue in loops, try to have them either right at the start or end, preferably at the start, so they are easy to spot and thus keeping the control flow easy to read.

    Another suggestion, wouldn’t having a chapter about understanding the flow of the loops be appropriate? I’m mostly thinking of things like is there an invariant (eg. int count tells us which numbers has been printed so far) and are there any termination conditions, so the loop can actually terminate. And also as you touch upon with the continue are there any control flow that can make the termination condition(s) inaccessible.

  • Todd

    Typo.

    In the first block of code you reference, all your function names begin with a capital letter (e.g., DoAddition), but these should begin with a lowercase letter by naming conventions (e.g., doAddition)

  • cpplx

    a lot of comments about the content of this lesson.
    mine will be about the use of the term "program" for a snippet
    and the usage of post(blah++) instead of pre(++blah) increment.
    minor things but they confuse me as a beginner in what is the proper way.
    i hope this comments are helpful for future updates and revisions instead of annoying :)

  • Niranjan

    Hi Alex,
    Really great tutorial. However I am one of those people who is just revisiting c++ to brush up the skills and avoiding the pitfalls. I think what would be great is if you can add a small box (with an icon indicating danger) around text items where you give advice about dangers and common mistakes. That way it is easy for people like me to browse through this faster and for newbs to remember.

    Thanks

Leave a Comment

  

  

  

12 + 6 =

Put C++ code inside [code][/code] tags to use the syntax highlighter