Search

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.

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 to the end of the loop body for the current iteration. This is useful when we want to terminate the current iteration early.

Here’s an example of using continue:

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

In the case of a for loop, the end-statement of the for loop still executes after a continue (since this happens after the end of the loop body).

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 jumps to the bottom. 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.

Here’s an example with a do-while loop using continue correctly:

This prints:

0 1 2 3 4 6 7 8 9

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 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

87 comments to 5.8 — Break and continue

  • Anmol sharma

    Sir, code mentioned below is not working and it is taken from your example which is mentioned above. It is working when i am using break; instead of continue. please check!

    int count(0);
    while (count < 10)
    {
        if (count == 5)
            continue; // jump to end of loop body
        std::cout << count << " ";
        ++count;

        // The continue statement jumps to here
    }

    • The text above the example explains it.
      "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!"

  • Dustin

    When I created this small bit of code to practice using continue, VS2017 required me to initialize "int count" outside of the for loop. Why? I originally wrote it in the init-statement, but I would get an error that "count" wasn't defined. **Edit: I can't seem to get the code tags to work. Not sure what I'm missing...

    #include <iostream>

    int main()
    {
        int count{ 0 };
        for (; count <= 50; ++count)
        {
            if ((count % 2) == 0)
                continue;
            else
                std::cout << count << std::endl;
        }
    }

    • Hi Dustin!

      [-CODE]
      int main()
      {
        ...
      }
      [-/CODE]
      without the -

      The following code is working. If it doesn't work for you, please share the exact error message, including the line number(s).

      • Dustin

        smh... I don't think I actually initialized it when I included it in the init statement. You're right. It's working.

        On an unrelated note, but still having to do with VS2017, while I'm going through these tutorials, I'm leaving VS up and creating small programs to experiment with what I'm learning. The other day, to mess with my son, I wrote a program in this VS2017 program window I always have open that asked the user for their name and if it matched my son's name, it would print out that he stunk. Otherwise, it would print out that the user didn't stink. (I know, it's juvenile). After I messed with him, I altered the code to say I stunk if the name input matched my name. What was odd is that even though I had deleted the code that told the program that if the string input matched my son's name the program was still recognizing when you entered his name and out put that he stunk. The program was still acting like the code was there!

        Have you ever had something like this happen where VS remembered code that you had deleted and executed it? I had saved the new code and I tried "cleaning" the project. It was like that comparison bit of code was still hanging out in the memory or something. Thoughts?

        • If old code gets stuck:
          - Make sure you restarted to program
          - Make sure you saved the changes (This happens too often)
          - Make sure you're building the project (VS can debug/run without re-building)
          - Clean the project (Delete everything that's not a code or project file)

          Some systems cache dynamic libraries. If you're developing one, disable/clean the cache or rename the library.

  • Anson

    Actually, break statement should be omitted in this way without using any variables.
    This was what my teacher told me.

    • Hi Anson!

      Your teacher is wrong. Your code will compare @ch to 'e' once in line 10 and once in line 14, without @ch changing in-between. This can introduce a significant performance overhead, depending on the loop-condition. On top of that, your sample has duplicate code, which can cause additional problems when updating the code. Both of Alex' snippets should be preferred over your teacher's solution.

      Your teacher has a valid point in not liking @break, because it can make understanding the control flow more difficult. You should not let this affect the efficiency or stability of your code!

  • In the "Break vs return" segment, there is a typo:

    It should be

    The output looks weird but the function name printed would be inline with the function name in the code.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]