break语句用于以下两种情况:
a)使用break语句立即退出循环。每当在循环内遇到break语句时,控制流就会直接从循环中退出。它与if语句一起使用,只能在循环内部使用(参见下面的示例),以便它仅在特定条件下发生。
b)用于switch-case控制结构。通常,在switch case中的所有情况都跟一个break语句,以避免后续的情况(参见下面的例子)执行。无论何时在switch-case块中遇到,控制流都从switch-case体中出来。
break语句的语法
break;
break语句流程图

示例 - 在while循环中使用break语句
在下面的示例中,我们有一个从 10 到 200 运行的while循环,但由于我们有一个在循环计数器,变量值达到 12 时遇到break语句,循环终止并且控制流跳转到程序中循环体之后的下一个语句。
#include <iostream>using namespace std;int main(){int num =10;while(num<=200) {cout<<"Value of num is: "<<num<<endl;if (num==12) {break;}num++;}cout<<"Hey, I'm out of the loop";return 0;}
输出:
Value of num is: 10Value of num is: 11Value of num is: 12Hey, I'm out of the loop
示例:for循环中的break语句
#include <iostream>using namespace std;int main(){int var;for (var =200; var>=10; var --) {cout<<"var: "<<var<<endl;if (var==197) {break;}}cout<<"Hey, I'm out of the loop";return 0;}
输出:
var: 200var: 199var: 198var: 197Hey, I'm out of the loop
示例:switch-case中的break语句
#include <iostream>using namespace std;int main(){int num=2;switch (num) {case 1: cout<<"Case 1 "<<endl;break;case 2: cout<<"Case 2 "<<endl;break;case 3: cout<<"Case 3 "<<endl;break;default: cout<<"Default "<<endl;}cout<<"Hey, I'm out of the switch case";return 0;}
输出:
Case 2Hey, I'm out of the switch case
在这个例子中,我们在每个case块之后都有break语句,这是因为如果我们没有它,那么后续的case块也会执行。没有break的同一程序的输出将是:
Case 2Case 3DefaultHey, I'm out of the switch case
