C++ break

In C++, the break statement is used to exit or terminate the execution of a loop or switch statement. When encountered within a loop or switch, the break statement causes the immediate termination of the enclosing loop or switch block, and control is transferred to the next statement after the loop or switch.

The break statement is often used in conjunction with conditional statements or loop control structures to exit prematurely under certain conditions. It allows you to control the flow of execution and avoid unnecessary iterations or checks. Here are the main use cases of the break statement:

Breaking Out of a Loop

The break statement can be used to exit a loop prematurely before its natural termination. When the break statement is encountered within a loop, the loop is immediately terminated, and the program continues with the next statement after the loop.

Example
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // Exit the loop when i is 5
    }
    cout << i << endl;
}

In this example, the loop will iterate from 0 to 4, and when i becomes 5, the break statement is encountered, causing the loop to terminate. The output will be 0 1 2 3 4.

Exiting a Switch Statement

In a switch statement, the break statement is used to exit the switch block after a specific case has been executed. It prevents the program from executing the subsequent cases and ensures that control moves to the next statement after the switch block.

Example
int choice = 2;

switch (choice) {
    case 1:
        cout << "You selected option 1." << endl;
        break;
    case 2:
        cout << "You selected option 2." << endl;
        break;
    case 3:
        cout << "You selected option 3." << endl;
        break;
    default:
        cout << "Invalid option." << endl;
        break;
}

In this example, when choice is 2, the corresponding case 2 block is executed, and the break statement immediately exits the switch block. As a result, the subsequent cases (case 3 and default) are not executed.

The break statement is essential for controlling the flow of execution in loops and switch statements. It allows you to break out of a loop prematurely or skip unnecessary checks in a switch statement. Proper usage of the break statement can help improve the efficiency and readability of your code.