Section 8.12 Breaking and Continuing
There are two special statements that can be used inside any kind of loop to change the normal flow of the loop:
break
and continue
. These statements are used to exit the loop early or skip the rest of the current iteration, respectively.
When
break
is encountered, the loop is immediately exited and the program continues with the statement following the loop. Try running this code sample and notice that when the value of i
is 3, the loop is exited early:
That example is kind of silly. We should just rewrite the test of the
for
loop to be i != 3
or i < 3
. It is more useful when you have complex logic in the loop body that that might either find a result or error that means there is no point in continuing the rest of the loop.
For example consider parsing a file of code. parsing is the process of breaking up structured text or data and forming a representation of what it contains. Compilers parse code files when they read the .cpp files we write and turn it into machine code that can run. If on a given line of code there is a bad error, the parser may decide it makes more sense to give up than to try to continue reading more. We could express this with something like:
while ( !endOfFile() ) {
// try to parse the current line
if (error_on_line) {
cout << "Error parsing file, giving up";
break;
}
// do some work based on line
// read the next line
}
The
continue
statement works like break, but instead of skipping to the end of the loop, it skips the rest of the body for this iteration, and then restarts the loop. This sample uses continue
to skip printing 3:
Note that this sample works because the for loop update always happens at the end of each iteration. Even if we use continue to stop it early. The sample below using a
while
has an infinite loop. When i
is 3 and we hit the continue
, the update on line 11 never gets to run. If you run it as is, it will keep running until the server decides to stop the program - at that point you will see 0 1 2
, the only numbers that got printed before the code got stuck. To fix it, you would have to add a line with ++i;
right before the continue to take us to the next value of i.
You have attempted of activities on this page.