C++ break Statement Usage & Examples
In C++, the break statement is used to prematurely end a loop or exit the execution of a switch statement.
In a loop, when the break statement is executed, the program will immediately exit the current loop and continue executing the code after the loop. This is commonly used to prematurely end the loop when a certain condition is met. For example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // 当 i 等于 5 时,提前结束循环
}
cout << i << " ";
}
// 输出:0 1 2 3 4
In a switch statement, the break statement is used to exit the execution of the switch statement and prevent the execution of other case branches. Without a break statement, the program will continue to execute the next case branch, which is known as “case fall-through”. For example:
int num = 2;
switch (num) {
case 1:
cout << "One ";
case 2:
cout << "Two ";
break; // 当 num 等于 2 时,跳出 switch 语句,防止继续执行下一个 case
case 3:
cout << "Three ";
}
// 输出:Two
It should be noted that the keyword “break” can only be used in loop statements and switch statements, not in other places.