The break Statement
The break statement
The break statement is typically used in loop statements and switch statements. When break is used within a switch statement, it allows the program to exit the switch block and execute the statements following the switch statement. Without a break statement, it would result in an infinite loop that cannot be exited. The usage of break within switch statements has been covered in previous examples when introducing switch statements, so no further examples will be provided here.
When the break statement is used within do-while, for, or while loop statements, it can terminate the loop and execute the statements following the loop. Typically, the break statement is always associated with an if statement. That is, the loop is exited when a certain condition is met.
Note:
- The break statement does not affect if-else conditional statements.
- In nested loops, a single break statement only exits the innermost loop.