C++ Break Statement

The break statement in C++ is used to exit a loop or switch-case immediately, skipping the remaining iterations or cases. It helps control program flow efficiently.

1. Break in Loops

The break statement can terminate a for, while, or do-while loop when a specific condition is met.

C++
#include <iostream>
using namespace std;

int main() {
    for(int i = 1; i <= 10; i++) {
        if(i == 5) {
            break; // exit the loop when i is 5
        }
        cout << i << " ";
    }
    return 0;
}

2. Break in Switch-Case

In switch-case, break is used to stop fall-through to the next case.

C++
#include <iostream>
using namespace std;

int main() {
    int day = 2;
    switch(day) {
        case 1:
            cout << "Monday" << endl;
            break;
        case 2:
            cout << "Tuesday" << endl;
            break;
        default:
            cout << "Other day" << endl;
    }
    return 0;
}

3. Common Mistakes

Using break outside loops or switch statements is invalid. Forgetting break in switch-case may cause unintended fall-through.

Conclusion

C++ break statement provides a way to exit loops or switch cases prematurely. Proper use ensures efficient control of program flow and prevents unwanted execution.