Free Hosting

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):
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>
 
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:
1
2
3
4
5
6
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:
1
2
3
4
5
6
7
8
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:
1
2
3
4
5
6
7
8
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
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.

0 comments:

Blogger Template by Clairvo