Understanding break and continue in C++

  • Last updated Apr 25, 2024

In C++, continue and break are control flow statements used within loops to control the flow of execution. They serve distinct purposes in loops, such as for, while, and do-while.

Break Statement

The break statement is used to terminate the current loop prematurely, and it is most commonly used to exit a loop when a certain condition is met. When break is encountered, the control immediately exits the loop, and the program continues executing the code after the loop.

Here's an example:

#include <iostream>

int main() {
    for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;  // The loop terminates when i equals 5.
    }
    std::cout << i << " ";
}
    return 0;
}

In this example, the loop will print numbers 1 to 10 and then exit when the value of i variable becomes 5.

The output of the above code is as follows:

1 2 3 4
Continue Statement

The continue statement is the same as the break statement. The only difference is that instead of terminating the loop and exiting from it, the continue statement skip the current iteration of the loop and move to the next iteration. It is often used when a specific condition should be skipped but the loop needs to continue.

Here's an example:

#include <iostream>

int main()
{
    for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers.
    }
    std::cout << i << " ";
}
    return 0;
}

In this example, the loop will print odd numbers from 1 to 9 while skipping even numbers.

The output of the above code is as follows:

1 3 5 7 9

These statements are valuable tools for controlling the flow of your C++ programs. Break allows you to exit a loop prematurely when a specific condition is met, while continue lets you skip the current iteration and move to the next one within the loop. These statements help you create more flexible and efficient loops in your C++ programs.