5.8 — Break and continue


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 switch statement, while loop, do while loop, or for loop to terminate. 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):

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

This program allows the user to type up to 80 characters (the standard length of a console line). If the user hits enter, the break causes the loop to terminate early.

Note that break can be used to get out of an infinite loop. The following program loops until the user hits enter:


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 continue with while or do while loops. Because these loops typically iterate 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 iii is 5, the if statement is true, and the loop returns back to the top. iii is never incremented. Consequently, on the next pass, iii 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 because it causes the execution flow to jump around. While this is certainly true, judicious use of break and continue can actually help make loops much more readable. For example, the following program prints all numbers from 0 to 99 which are not divisible by 3 or 4, and then prints out how many numbers were found that meet this criteria:

However, this can be rewritten as the following, which is easier to read:

Keeping the number of nested blocks down often improves code readability more than a break or continue harms it. For that reason, your author is generally in favor of using break and continue when and where it makes the code easier to understand.

5.9 -- Random number generation
5.7 -- For statements

30 comments to 5.8 — Break and continue

  • perouf

    In the first example of the continue statemant you say that:
    This program prints all of the numbers from 0 to 19 that aren’t divisible by 4.
    But its exactly the other way. All the numbers that are divisible by 4 get printed.
    In the example after that, the program only prints: 1 2 3 4 and then its stuck.
    regards Perouf

    [ Fixed! Thanks for noticing. -Alex ]

  • Zomgie

    In your second code example, you start with #include but forget to add in

    using namespace std;

    Just a note, it made it confusing for those wanting to try out the code via execution.

    edit: Also, it seems that escaping the newline character was unnecessary. Checking for

    returned the following error whereas

    executed cleanly.

    test.cpp:16:23: warning: multi-character character constant
    test.cpp: In function β€˜int main()’:
    test.cpp:16: warning: comparison is always false due to limited range of data type

    • I fixed the issue with the using namespace std -- thanks. Escaping the newline character should be necessary, as ‘\n’ and ‘n’ are two completely different characters. I note that in my examples above, ‘\n’ was listed as ‘\\n’, which I have also fixed.

  • Thomas

    Hello Alex,

    Your first code example on how to use break and continue returns all numbers which can be divided by 3 and 4, while it is meant to do the opposite, shouldn’t it be without the ‘!’s?


    [ You are correct. Thanks for noticing. -Alex ]

  • chkwa

    this is just a correction.

    “For example, the following program prints all numbers from 0 to 99 which are not divisible by 3 or 4, and then prints out how many numbers were found that meet this criteria:”

    int nPrinted = 0;

    • I believe it is correct as written.

    • Sergio Ramos

      6 year’s later (lol)…. I’m here having the same issue as chkwa so I wanted to clarify and verify my understanding. Looking over the code, using “&&” is the correct way to do this.

      This goes back to the “3.6 β€” Logical operators” explaining that this “if” statement will only iterate if both operands ((iii % 3)&&(iii % 4)) are true (non zero). Here, either %3 or %4 will cause the whole logical operator to become false (zero), and the iterated numbers (iii) in question at the time, will be ignored. Leaving you with what was expected, “…prints all numbers from 0 to 99 which are not divisible by 3 or 4, and then prints out how many numbers were found…”

      Thank you, and have a nice day! :)

  • mon

    please help me create a C++ program that will allow the user to input the number of students, name and score and finally displays the name with highest scores…

    say for example:

    input number of students = 10, it allows you to input name and scores 10 times. and finally it will print the highest score with name…


  • kevin

    In the second example, it seems like the nCount would be reset to zero every time, so that the for loop would never reach nCount = 80 and stop. That’s what happened when I tried to run it. I’m wondering if I am misunderstanding the example. When I run the script, it only breaks if I type an enter.

  • zeb Noon

    Hye Alex!
    My question is “why you are using “nPrinted” int variable in your last two examples?

  • Echo51

    In your first example, i get the error that when i compile it with Code:blocks, i can only press a button and send it once, before the “press enter to continue” message appears, terminating the window. this is anooying me as im making a Text RPG

  • Ant

    In the second example, doesn’t the line buffer take over and not count each individual character entered until you hit enter which breaks the loop?

  • (wrong comment… could you delete it? Thanks)

  • Farhad

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

  • sudhir kumar

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

  • alwin

    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?

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

    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.


  • Najla

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

  • 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

    was replaced by

  • Moogie


    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! :)

  • lharriger

    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 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:
    Keep in mind this example uses "windows.h" library and it will only work for windows based apps.

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

  • DrSuse

    Considering this little snippet:

    int iii=0;
    while (iii < 10)
    if (iii==5)
    cout << 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.

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

  • Jatn

    Sir please can you further explain getchar () function . I can’t understand how you used it in loop and count number of spaces . what is the basic difference between getchar and cin for inputting chars, i googled it but can’t find something useful. thanks in advance

  • Todd


    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)

Leave a Comment




10 − five =

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