Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Break and Continue in C++

Introduction

In C++, the break and continue statements are used to control the flow of loops. These statements provide more control over the loop execution and can enhance the efficiency of your code. Understanding how to use them effectively is crucial for writing optimal and readable C++ programs.

The break Statement

The break statement is used to exit a loop prematurely. When the break statement is encountered inside a loop, the loop is immediately terminated, and the program control resumes at the next statement following the loop.

Here's the syntax:

break;
                

Let’s look at an example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            break;
        }
        cout << "i: " << i << endl;
    }
    return 0;
}
                

Output:

i: 0
i: 1
i: 2
i: 3
i: 4

In this example, the loop terminates when i equals 5, so the numbers 0 through 4 are printed.

The continue Statement

The continue statement is used to skip the current iteration of a loop and proceed with the next iteration. When the continue statement is encountered, the remaining statements in the loop body are skipped, and the loop proceeds with the next iteration.

Here's the syntax:

continue;
                

Consider the following example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            continue;
        }
        cout << "i: " << i << endl;
    }
    return 0;
}
                

Output:

i: 0
i: 1
i: 2
i: 3
i: 4
i: 6
i: 7
i: 8
i: 9

In this example, when i equals 5, the continue statement skips the rest of the loop body and proceeds with the next iteration, so the number 5 is not printed.

Using break and continue Together

You can use both break and continue statements within the same loop to control the flow effectively. Here is an example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 10; i++) {
        if (i == 3) {
            continue;
        }
        if (i == 7) {
            break;
        }
        cout << "i: " << i << endl;
    }
    return 0;
}
                

Output:

i: 0
i: 1
i: 2
i: 4
i: 5
i: 6

In this example, when i equals 3, the continue statement skips the rest of the loop body, and when i equals 7, the break statement terminates the loop.

Conclusion

Understanding and using the break and continue statements effectively can greatly improve the readability and efficiency of your code. The break statement is used to exit a loop prematurely, while the continue statement is used to skip the current iteration and continue with the next iteration. Practice using these statements in different scenarios to get a good grasp of their functionality.