break语句
作用: 用于跳出==选择结构==或者==循环结构==
break使用的时机:
- 出现在switch条件语句中,作用是终止case并跳出switch
- 出现在循环语句中,作用是跳出当前的循环语句
- 出现在嵌套循环中,跳出最近的内层循环语句
1 int main() { 2 //1、在switch 语句中使用break 3 cout << "请选择您挑战副本的难度:" << endl; 4 cout << "1、普通" << endl; 5 cout << "2、中等" << endl; 6 cout << "3、困难" << endl; 7 8 int num = 0; 9 10 cin >> num; 11 12 switch (num) 13 { 14 case 1: 15 cout << "您选择的是普通难度" << endl; 16 break; 17 case 2: 18 cout << "您选择的是中等难度" << endl; 19 break; 20 case 3: 21 cout << "您选择的是困难难度" << endl; 22 break; 23 } 24 25 system("pause"); 26 27 return 0; 28 }
1 int main() { 2 //2、在循环语句中用break 3 for (int i = 0; i < 10; i++) 4 { 5 if (i == 5) 6 { 7 break; //跳出循环语句 8 } 9 cout << i << endl; 10 } 11 12 system("pause"); 13 14 return 0; 15 }
1 int main() { 2 //在嵌套循环语句中使用break,退出内层循环 3 for (int i = 0; i < 10; i++) 4 { 5 for (int j = 0; j < 10; j++) 6 { 7 if (j == 5) 8 { 9 break; 10 } 11 cout << "*" << " "; 12 } 13 cout << endl; 14 } 15 16 system("pause"); 17 18 return 0; 19 }
continue语句
**作用:**在==循环语句==中,跳过本次循环中余下尚未执行的语句,继续执行下一次循环
-
1 int main() { 2 3 for (int i = 0; i < 100; i++) 4 { 5 if (i % 2 == 0) 6 { 7 continue; 8 } 9 cout << i << endl; 10 } 11 12 system("pause"); 13 14 return 0; 15 }
注意:continue并没有使整个循环终止,而break会跳出循环
goto语句
**作用:**可以无条件跳转语句
语法: goto 标记;
**解释:**如果标记的名称存在,执行到goto语句时,会跳转到标记的位置
1 int main() {
2
3 cout << "1" << endl;
4
5 goto FLAG;
6
7 cout << "2" << endl;
8 cout << "3" << endl;
9 cout << "4" << endl;
10
11 FLAG:
12
13 cout << "5" << endl;
14
15 system("pause");
16
17 return 0;
18 }
注意:在程序中不建议使用goto语句,以免造成程序流程混乱
// 本节内容来自黑马程序员,仅供学习交流,侵删; https://github.com/AnkerLeng/Cpp-0-1-Resource/blob/master/%E7%AC%AC1%E9%98%B6%E6%AE%B5C%2B%2B%20%E5%8C%A0%E5%BF%83%E4%B9%8B%E4%BD%9C%20%E4%BB%8E0%E5%88%B01%E5%85%A5%E9%97%A8/C%2B%2B%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8%E8%AE%B2%E4%B9%89/C%2B%2B%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8.md#43-%E8%B7%B3%E8%BD%AC%E8%AF%AD%E5%8F%A5
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了