7.10 — Break and continue


Although you have already seen the break statement in the context of switch statements (7.4 -- Switch statement basics), it deserves a fuller treatment since it can be used with other types control flow statements as well. The break statement causes a while loop, do-while loop, for loop, or switch statement to end, with execution continuing with the next statement after the loop or switch being broken out of.

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 fallthrough into subsequent cases):

See lesson 7.5 -- Switch fallthrough and scoping for more information about fallthrough, along with some additional examples.

Breaking a loop

In the context of a loop, a break statement can be used to end the loop early. Execution continues with the next statement after the end of the loop.

For example:

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

Here’s a sample execution of the above program:

Enter a number to add, or 0 to exit: 5
Enter a number to add, or 0 to exit: 2
Enter a number to add, or 0 to exit: 1
Enter a number to add, or 0 to exit: 0
The sum of all the numbers you entered is: 8

Break is also a common way to get out of an intentional infinite loop:

A sample run of the above program:

Enter 0 to exit or anything else to continue: 5
Enter 0 to exit or anything else to continue: 3
Enter 0 to exit or anything else to continue: 0
We're out!

Break vs return

New programmers sometimes 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.

Here are two runs of this program:

Enter 'b' to break or 'r' to return: r
Function breakOrReturn returned 1
Enter 'b' to break or 'r' to return: b
We broke out of the loop
Function breakOrReturn returned 0


The continue statement provides a convenient way to end the current iteration of a loop without terminating the entire loop.

Here’s an example of using continue:

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


Continue statements work by causing the current point of execution to jump to the bottom of the current loop.

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. These loops typically change the value of variables used in the condition inside the loop body. If use of a continue statement causes these lines to be skipped, then the loop can 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 continue causes the execution to jump to the bottom of the loop. 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.

Of course, you already know that if you have an obvious counter variable, you should be using a for loop, not a while or do-while loop.

The debate over use of break and continue

Many textbooks caution readers not to use break and continue in loops, 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 its value is changed), an else statement, and a nested block.

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

Best practice

Use break and continue when they simplify your loop logic.

The debate over use of early returns

There’s a similar argument to be made for return statements. A return statement that is not the last statement in a function is called an early return. Many programmers believe early returns should be avoided. A function that only has one return statement at the bottom of the function has a simplicity to it -- you can assume the function will take its arguments, do whatever logic it has implemented, and return a result without deviation. Having extra returns complicates the logic.

The counter-argument is that using early returns allows your function to exit as soon as it is done, which reduces having to read through unnecessary logic and minimizes the need for conditional nested blocks, which makes your code more readable.

Some developers take a middle ground, and only use early returns at the top of a function to do parameter validation (catch bad arguments passed in), and then a single return thereafter.

Our stance is that early returns are more helpful than harmful, but we recognize that there is a bit of art to the practice.

Best practice

Use early returns when they simplify your function’s logic.

7.11 -- Halts (exiting your program early)
7.9 -- For statements

108 comments to 7.10 — Break and continue

  • Lesommeil

    Continue and break relate to goto?  They could almost do the same job.
    And are they the same as unconditional jump?

  • James C

    Wording suggestion:

    In this part of the first paragraph:

    "it deserves a fuller treatment since it can be used with other types of loops as well."

    Since it's referring to the switch statement, which isn't a loop, I think "loops" in the sentence should be replaced with "control flow statements", or something like that.

  • Enrico

    Maybe it could be pointed out that one of the pro of a function that has only one final return statement is related to letting the compiler use RVO return value optimization.

    If I remember correctly multiple returns makes harder for the RVO to get efficiently applied, but not so sure if it's still true.

    Although this is no more a significant performance issue nowadays thanks to move semantic.

  • Behersker

    On line 11 in the second to last program:

    std::cin >> ch{};

    Should read

    std::cin >> ch;

  • Waldo Lemmer

    Yet another great lesson :D

    Section "Continue", first snippet, line 12:

    `'\n'` should be used instead of `std::endl` to avoid unnecessary buffer flushes (as you've taught us :)).

    Section "The debate over use of break and continue", second snippet, line 9:

    `ch` should be initialized.

  • Patrick

    In the previous lesson, you guys provided an equivalent of the for loop using while:

    Since the end-statement of a for loop executes after the loop body, should we think of it as technically NOT being apart of this following block?:

    and instead being done implicitly after the body?

  • Tobito

    Unable to start program
    Operation did not complete successfully because the file contain a virus or potentially unwanted software

    what is wrong with this code? everytime i had compiled it and my windows antivirus detect a trojan LOL

    • Tobito

      line 5 ++i
      line 8 +=

      i don't known why the ++ is missing after i had posted to the comment

      • Tobito

        Today i am trying the same code, it's not showing the error from detecting virus.

        when i debug step into on line 5, why it showing the value -858993460?

        why the return 0 is showing <=4ms elapsed, but the other line is showing <=1ms elapsed? the longer elapsed time which showing when at debugging on step into, will it means the more slower the performance will be when we make that code into a programs?

        • Sahil

          The random number that you see when debugging on line 5 is probably garbage data that is stored at the address that is allocated for the variable "i". You ARE on line 5 (it hasn't been executed yet), once you move to the next line i.e line 6, Line 5 has been executed and your variable has been initialized.

          Basically what your compiler does is that it creates the variables first thing, and then initializes them one the particular line has been executed. You can see this behavior in the following program.

          You'll get warnings as we are not doing anything with the variables, but when you run this in debug mode, you'll see that even when you are on line 3, the debug window still shows all 3 variables (which are not initialized yet) now step through to the next line and "a" will be initialized.

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

  • arsonlol

    hello i really dont understand what does the == 0 do here

    if ((count % 4) == 0)

  • comment

    Not sure, if this has been mentioned already, but there are 2 issues in the "Continue" section:

    Second code snippet:

    That comment is misleading; the statements IS executed during the first 5 iterations of the loop.

    Furthermore the output of the third code snippet should be

    too, since the cout line is skipped in iterations 6 to 10

    • nascardriver

      > the statements IS executed during the first 5 iterations of the loop.
      Comment amended, thanks!

      > Furthermore the output of the third code snippet should be
      The third snippet in the "continue" section? That's correct as written. The condition is `i == 5`, not `i >= 5`.

  • Benur21

    Could also include exit() which is used to skip the rest of the program

  • Benur21


    return is used to skip the current function;
    break is used to skip the current loop or switch;
    continue is used to skip the rest of the current iteration.

  • 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 << " ";

        // 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!"

    • Andrew

      The reason that the code is not working as the example is beacause the C++ is executed sequential, by it's nature. So, in the case when count is 5, the while condition is evaluated as true, after that if condition is evaluated as true, the continue statement is executed, witch will jump to the end of while loop (in other words will skip the rest of the body of while loop), and from this moment the loop become infinite.
      When continue statement is meet end executed, the std::cout part will be skiped.
      Even if you introduce continue statement of the if statement inside of {}, the result will be the same.

      You will see, if you change the possition of if statement, after std::cout, the output will be 0 1 2 3 4 5 5 5 5 ....

      Excuse the bad english, and correct me if I'm wrong or I misunderstood.

  • 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)
                std::cout << count << std::endl;

    • Hi Dustin!

      int main()
      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]