C++ - C++ Break and Continue - Programming Languages

Demystifying the Break and Continue Statements in C++

Control flow statements are fundamental to any program. These instructions make programs dynamic, enabling them to behave differently based on what we input. While some statements like ifelse are ubiquitous and easy to grasp, others require a more nuanced understanding of control flow. 

In this article, we’ll cover the C++ continue and break statements and explain how you can use them to write better code.

The Control Flow of a Computer Program

A computer program can be thought of as a collection of statements and instructions. These may be executed sequentially — one statement after another, or in an unordered manner, depending on whether the conditions for their execution are met. This order of execution is referred to as control flow. 

As an aspiring C++ developer, you might already be familiar with some control flow statements. One of the simplest of these is the if-else statement. It’s used to branch a program’s logic into one path if a condition is met, or into another path if otherwise.

An if-else statement in C++ might look as follows:

if (condition is true) {
    do this;
}
else {
    do this;
}

Loops comprise another basic example of control flow. A for-loop executes a block of statements a predefined number of times, whereas a while-loop executes a block of statements so long as the applicable condition holds true.

These loops might look as follows:

for (counter n) {
    execute this n number of times;
}
while (condition) {
    execute this for as long as the condition holds;
}

For and while-loops in combination with if-else statements can be used to express complex program logic. However, this logic can sometimes get so complex that it makes the code hard to read. Once the programmers have trouble reading a piece of software, maintenance becomes a real challenge.

On other occasions, we may want to alter the flow of a standard loop. For example, we may want to skip a current iteration or even terminate a whole loop prematurely. We can certainly employ continue and break C++ statements in these scenarios.

The Continue Statement

The continue statement is used within a loop to skip the rest of the code in the current iteration and advance the loop to the next iteration. It’s a single keyword statement that must be placed within the body of a loop or a switch statement. continue typically placed within an if-else statement that has a condition for executing the iteration.

Consider this example that illustrates the syntax and usage of the C++ continue statement:

for(int num = 1; num < 100; num++){
    if (num % 7 != 0) {
        continue;
    }
    std::cout << num << std::endl;
}
// Output:
7
14
21
28
...

In the program above, we’re printing out numbers that are multiples of seven. If the condition within the if-statement is evaluated to be true (or, in other words, if the remainder of division between num and 7 does not equal 0), the program executes the continue statement, causing the rest of the code in the loop to be ignored in the current iteration. Thus, the program only gets to execute the print statement for the numbers that are multiples of 7, and skips over the code that does the printing for the numbers that are not.

The Break Statement

Whereas continue only skips over a current iteration, the break C++ statement terminates the entire loop. break is a single keyword that must be placed within a loop or switch statement. It’s generally used to exit a loop when the predetermined condition for terminating the loop becomes true. Here’s the break statement in action:

int num = 1;
while(true){
    if (num % 7 == 0 && num % 12 == 0 && num % 37 == 0){
        break;
    }
    num++;
}
std::cout << num << std::endl;
// Output:
3108

In this example, we used a while-loop to find the smallest number that’s a multiple of 7, 12 and 37. Each iteration of the loop increases the number by 1 and checks if the condition holds. As soon the program finds the number, it executes the break statement, skipping the rest of the code in the current iteration before terminating the loop. Once the loop terminates, the program resumes execution — at the line where you’ll see the result of 3108.

Should we use continue, break or if-else?

Fundamentally, break and continue do not fulfill any function that can’t be expressed with nested loops and if-else statements. Let’s take the example from earlier, this time restating it so that it does not use a continue statement: 

for(int num = 1; num < 100; num++){
    if (num % 7 == 0) {
        std::cout << num << std::endl;
    }
}
// Output:
7
14
21
28
...

The two programs do the same thing. However, the value in using the continue statement lies in the fact that it can reduce complexity and improve code readability. Although this code snippet is too simple to illustrate its full potential, continue at the beginning of a loop generally acts as a precondition for executing the rest of the loop, and you can read such statement as, “if this statement is true, ignore the rest of the code and skip to the next iteration.” This is especially helpful for complex loops or loops that contain multiple nested if-else statements, like the following example:

for(unsigned int i = 0; i < sizeof(foods); i++ ){
    if(!foods[i].isVegetarian()){
        if(!foods[i].hasLeafyGreens()){
            if(!foods[i].containsGluten()){
            // and so on…            // the rest of the code
            }
        }
    }
}

Now, consider the same program, but with continue statements:

for(unsigned int i = 0; i < sizeof(foods); i++ ){
    if(foods[i].isVegetarian()) continue;
    if(foods[i].hasLeafyGreens()) continue;
    if(foods[i].containsGluten()) continue;
    // the rest of the code
    }

Although we could nest the if-statements indefinitely and our logic would still make sense, using a C++ continue statement yields a solution that’s easier to understand, modify and debug.

Good Practices When Using continue and break

Programmers have somewhat mixed feelings about continue and break statements. When used sensibly, these statements can be valuable tools for making your code more succinct. However, they tend to be overused and thus add complexity to code. 

We’ve mentioned in the previous section that these statements can enhance readability when placed at the beginning of a loop. However, placing continue and break in the middle of a code block is not always advised as they might easily be missed, or it might not be obvious to the programmer which loop they belong to. 

Let’s take a look at a made-up code snippet:

void some_function(){
    while(true){
        // some code
        for(int i = 0; i < another_num; i++){
            var = foo();
            while(!var) {
                bar();
                // more code
                if(condition) break;
            }
            foo();
        }
        if(another_condition) return;
    }
}

Did you notice the break statement hidden deep in the code? If this code were to be read by any programmer other than the one who wrote it, it might take them a while to figure out the scope of the condition or the loop the break statement belongs to. 

This might not seem like a big deal so long as the program’s logic is correct. However, as a code base grows larger and more people become involved in a project, it becomes increasingly important for the code to be readily understood by everyone and not just the one person who wrote it. For this reason, we want to avoid placing hidden traps in code.

Overusing break statements is also bad practice because it introduces more exit points. We generally want to keep exit points to a minimum since multiple exit points complicate our logic and make it more difficult to comprehend code. Additionally, increased reliance on continue and break C++ statements makes it difficult for a loop to perform optimally. CPUs perform best when there is a predictable flow in a loop.

Master C++ Online

In this article, we covered C++ continue and break statements and explained why every developer should have them in their arsenal. We hope you’ll continue learning this fascinating language.

As part of our specialized C++ Nanodegree program, we’ll take you through the ins and outs of C++ and give you the opportunity to work through five real-world projects.

Sign up to become a C++ developer!

Start Learning