C++ Break Statement

The break statement in C++ is used to exit from a loop or a switch statement prematurely. When executed, it terminates the nearest enclosing loop or switch statement and transfers control to the statement following the loop or switch block.

Syntax:

break;

The break statement does not return any value; it simply transfers control out of the current loop or switch statement.

Example: Using break in a Loop

The break statement does not return any value; it simply transfers control out of the current loop or switch statement.

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 10; ++i) {
        if (i == 5) {
            break; // Exit the loop when i is 5
        }
        cout << "i = " << i << endl;
    }
    cout << "Loop terminated." << endl;
    return 0;
}

Output:

i = 0
i = 1
i = 2
i = 3
i = 4
Loop terminated.

In this example, the loop breaks when i equals 5, so the loop terminates before i reaches 10.

C++ Break Statement with Inner Loop

When using break in nested loops, it only affects the innermost loop where it is used. The outer loops continue to execute as normal.

Example: Break Statement in Inner Loop

In this example, the break statement is used within the inner loop, causing only the inner loop to terminate:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 3; ++i) {
        cout << "Outer loop iteration: " << i << endl;
        for (int j = 0; j < 3; ++j) {
            if (j == 1) {
                break; // Exit only the inner loop when j is 1
            }
            cout << " Inner loop iteration: " << j << endl;
        }
    }
    return 0;
}

Output:

Outer loop iteration: 0
Inner loop iteration: 0
Outer loop iteration: 1
Inner loop iteration: 0
Outer loop iteration: 2
Inner loop iteration: 0