Search

7.10 — Break and continue

Break

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 of loops 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 %Failed lesson reference, id XX% 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

Continue

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:

1
2
3
5
6
7
9

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.


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

40 comments to 7.10 — Break and continue

  • dog44wgm

    Just want to point out that the "next" link for "5.8 Break and continue" should be "5.9 Random number generation" and not "6.1 — Arrays (Part I)".

    BTW, this is what a tutorial ought to be, good job.

    My 2 cents: I'd like to see the many "fix-it" comments (like this one) put aside somewhere so they don't obscure the other conversations which can be very illuminating.

  • lharriger

    THE PROBLEM:
    As mentioned by others, the example that uses the getchar() function will not terminate after 80 keystrokes. This is because the getchar() function uses something called line buffering, ie: characters are only transmitted to the machine when a new line character (Enter) is encountered. This means that as soon as the program processes the getchar() command it will create a buffer and as you type this buffer will expand until you hit Enter. The program then loops through each character of the buffer. Thus the program will terminate for two possible reasons:

    1)The buffer is fewer than 80 characters in which case it will hit the end of the buffer and the break command is called since the line buffer always terminates with '\n'.

    2) The buffer is greater than 80 characters in which case the loop simply terminates without hitting the end of the buffer. (Note that in this second case the break command is never executed.)

    Note that case 2) will quit counting up spaces after 80 strokes, hence Alex's program only covers case 1).

    THE FIX:
    1) Replace getchar() with getch(). The getch() function is unbuffered.
    2) You will need to #include "conio.h" at the top to use this function.
    3) '\n' must be replaced by its ASCII value of 13 in the if statement.
    4) As a last touch you should include cout << chChar; in the body of the loop. This is because getch() does not "echo" input like getchar() does.

    THE DISCLAIMER:
    The conio.h library is very unstable and should be used with extreme caution. Some goes as far as to say NEVER use it. Unfortunately, the C++ standard library does not include an unbuffered function like getch. However, there are functions out there written by C++ user to mimic getch(). Here is a link to one example:
    http://www.dreamincode.net/code/snippet2415.htm
    Keep in mind this example uses "windows.h" library and it will only work for windows based apps.

  • Moogie

    Hi,

    Just wanted to lend my voice to those pointing out the problem with the second example. Perhaps it needs rewording?

    Utilising only the lessons taught so far (i.e. using cin to capture user input), there's no way this for loop works. I've been following these (extremely well-written and helpful!) tutorials myself, as I've only recently begun my journey towards learning C++, and I too ran this example and confirmed that no matter how many spaces or letters I entered the loop never exits, because I never actually send (cin >>) the inputs.

    Perhaps there's another method you were thinking of when writing that particular example, that does not work using cin..?

    P.S. I absolutely love this site. Thank you for all the hard work that's gone into building such a comprehensive archive of knowledge! :)

  • bla

    I think the readability examples are "manipulated" to argue pro continue statements: The example without continue would be easier to read, if the statement

     iii % 3 

    was replaced by

     iii % 3 != 0 
  • Najla

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

  • dhysk

    I finally got it, although a different example or an explanation(A better option) may help newbs like me. Judging by a few of the comments above I'm not the only one that had an issue understanding it. However I think I have it now maybe?

    In you're 'messy' example I (and at least one other guy) just didn't get the if statement:

    if ((iii % 3)&&(iii % 4))
    

    for the life of me it took me a few minutes to get it because new guys think of using some kind of comparison ,=, ect. You are using a simple logic and statement. So when (iii % 3) evaluates to any thing but 0 (meaning its divisible by that integer) that section will go be evaluated in the logic statement to a 1. Only by being evenly divisible will it go to a 0 their for making either a 0&&1 or 0&&0 logic operation both resulting in a 0 or FALSE.

    example

        // messy!
        int iii = 8;
        if ((iii % 3)&&(iii % 4))   // evaluate like this: if ((2)&&(0)) ===>  if (1&&0) ===> if (0) 
        {
           cout << "oops";          // this will never run since its false
        }
    
  • alwin
    int nPrinted = 0;
    
    for (int iii=0; iii < 100; iii++)
    {
        // if the number is divisible by 3 or 4, skip this iteration
        if ((iii % 3)==0 || (iii % 4)==0)
            continue;
    
        cout << iii << endl;
        nPrinted++;
    }
    
    cout << nPrinted << " numbers were found" << endl;
    

    shouldn't "if ((iii % 3)==0 || (iii % 4)==0)" be "if ((iii % 3)==0 && (iii % 4)==0)" as we are testing to see whether "iii" is not divisible by both 3 and 4 not 3 or 4?

  • sudhir kumar

    material given by learncpp.com is really fully satisfied . student can easily understand concepts through this.

  • Farhad

    above the page, 'next post' takes you to 6.1-arrays and not 5.9-random number generation !!!

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">