Navigation



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

switch (chChar)
{
    case '+':
        DoAddition(x, y);
        break;
    case '-':
        DoSubtraction(x, y);
        break;
    case '*':
        DoMultiplication(x, y);
        break;
    case '/':
        DoDivision(x, y);
        break;
}

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

#include <cstdio> // for getchar()
#include <iostream>

using namespace std;

int main()
{
    // count how many spaces the user has entered
    int nSpaceCount = 0;

    // loop 80 times
    for (int nCount=0; nCount < 80; nCount++)
    {
        char chChar = getchar(); // read a char from user

        // exit loop if user hits enter
        if (chChar == '\n')
            break;

        // increment count if user entered a space
        if (chChar == ' ')
            nSpaceCount++;
    }

    cout << "You typed " << nSpaceCount << " spaces" << endl;

    return 0;
}

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:

while (1)
{
    char chChar = getchar();
    if (chChar == '\n')
        break;
}

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:

for (int iii=0; iii < 20; iii++)
{
    // if the number is divisible by 4, skip this iteration
    if ((iii % 4) == 0)
        continue;

    cout << iii << endl;
}

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:

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

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:

int nPrinted = 0;

for (int iii=0; iii < 100; iii++)
{
    // messy!
    if ((iii % 3) && (iii % 4))
    {
        cout << iii << endl;
        nPrinted++;
    }
}

cout << nPrinted << " numbers were found" << endl;

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

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;

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

  • [...] 2007 Prev/Next Posts « 5.6 — Do while statements | Home | 5.8 — Break and continue » Monday, June 25th, 2007 at 6:48 [...]

  • 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

    '\n'

    returned the following error whereas

    'n'

    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.

  • [...] 5.8 — Break and Continue  Print This Post This entry is filed under C++ Tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. No Responses to “5.9 — Random number generation” [...]

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

    e.g.

    int nPrinted = 0;
    
    for (int iii=0; iii < 100; iii++)
    {
        // messy!
        if ((iii % 3) && (iii % 4))
        {
            cout << iii << endl;
            nPrinted++;
        }
    }
    
    cout << nPrinted << " numbers were found" << endl;
    
    

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

    for (int iii=0; iii < 100; iii++)
    {
        // messy!
        if ((iii % 3)&&(iii % 4)) //may be it should be ||(or) and not &&(and)
        {
            cout << iii << endl;
            nPrinted++;
        }
    }
    
    cout << nPrinted << " numbers were found" << endl;
    
  • 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…

    thanks

  • 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 learncpp.com is really fully satisfied . student can easily understand concepts through this.

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

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

     iii % 3 

    was replaced by

     iii % 3 != 0 
  • 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! :)

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

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

  • [...] Singh, Novice programmer, a game freak…!!!Novice programmer, a game freak…!!! Checkout the link http://www.learncpp.com/cpp-tuto…It should help…Embed QuoteUpvote • Comment Loading… • Written just now Add your [...]

You must be logged in to post a comment.