Search

Meta

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

#include <cstdio> // for getchar()

#include <iostream>

usingnamespacestd;

intmain()

{

// count how many spaces the user has entered

intnSpaceCount=0;

// loop 80 times

for(intnCount=0;nCount<80;nCount++)

{

charchChar=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;

return0;

}

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:

1

2

3

4

5

6

while(1)

{

charchChar=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:

1

2

3

4

5

6

7

8

for(intiii=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:

1

2

3

4

5

6

7

8

intiii=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:

1

2

3

4

5

6

7

8

9

10

11

12

13

intnPrinted=0;

for(intiii=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:

1

2

3

4

5

6

7

8

9

10

11

12

13

intnPrinted=0;

for(intiii=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.

Share this:

27 comments to 5.8 — Break and continue

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

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.

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

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.

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

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:

1

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

1

2

3

4

5

6

// messy!

intiii=8;

if((iii%3)&&(iii%4))// evaluate like this: if ((2)&&(0)) ===> if (1&&0) ===> if (0)

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!

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.

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.