break
statement
| General topics | ||||||||||||||||
| Flow control | ||||||||||||||||
| Conditional execution statements | ||||||||||||||||
| Iteration statements (loops) | ||||||||||||||||
|
||||||||||||||||
| Jump statements | ||||||||||||||||
|
||||||||||||||||
| Functions | ||||||||||||||||
| Function declaration | ||||||||||||||||
| Lambda function expression | ||||||||||||||||
inline
specifier
|
||||||||||||||||
| Dynamic exception specifications ( until C++17* ) | ||||||||||||||||
noexcept
specifier
(C++11)
|
||||||||||||||||
| Exceptions | ||||||||||||||||
| Namespaces | ||||||||||||||||
| Types | ||||||||||||||||
| Specifiers | ||||||||||||||||
|
||||||||||||||||
| Storage duration specifiers | ||||||||||||||||
| Initialization | ||||||||||||||||
| Expressions | ||||||||||||||||
| Alternative representations | ||||||||||||||||
| Literals | ||||||||||||||||
| Boolean - Integer - Floating-point | ||||||||||||||||
| Character - String - nullptr (C++11) | ||||||||||||||||
| User-defined (C++11) | ||||||||||||||||
| Utilities | ||||||||||||||||
| Attributes (C++11) | ||||||||||||||||
| Types | ||||||||||||||||
typedef
declaration
|
||||||||||||||||
| Type alias declaration (C++11) | ||||||||||||||||
| Casts | ||||||||||||||||
| Memory allocation | ||||||||||||||||
| Classes | ||||||||||||||||
| Class-specific function properties | ||||||||||||||||
|
||||||||||||||||
| Special member functions | ||||||||||||||||
|
||||||||||||||||
| Templates | ||||||||||||||||
| Miscellaneous | ||||||||||||||||
导致所在的 for 、 range-for 、 while 或 do-while 循环,或者 switch 语句 终止。
当使用条件表达式和条件语句来终止循环显得不便时使用。
目录 |
语法
attr
(可选)
break
;
|
|||||||||
| attr | - | (since C++11) 任意数量的 属性 |
说明
仅出现在循环体(
while
、
do-while
、
for
)的
语句
中,或出现在
switch
的
语句
中。
执行该语句后,控制权将转移到紧接外层循环或switch之后的语句。与任何块退出情况相同,在外层循环之后的首行代码执行之前,所有在外层复合语句或循环/switch
条件
中声明的自动存储对象,将按照构造顺序的逆序被销毁。
注释
break 语句不能用于跳出多重嵌套循环。要实现此目的,可使用 goto 语句 。
关键词
示例
#include <iostream> int main() { int i = 2; switch (i) { case 1: std::cout << "1"; // <---- 可能警告:贯穿 case 2: std::cout << "2"; // 执行从此 case 标签开始(+警告) case 3: std::cout << "3"; // <---- 可能警告:贯穿 case 4: // <---- 可能警告:贯穿 case 5: std::cout << "45"; // break; // 后续语句的执行被终止 case 6: std::cout << "6"; } std::cout << '\n'; for (char c = 'a'; c < 'c'; c++) { for (int i = 0; i < 5; i++) // 仅此循环受 break 影响 { // if (i == 2) // break; // std::cout << c << i << ' '; // } } std::cout << '\n'; }
可能的输出:
2345 a0 a1 b0 b1
参见
[[
fallthrough
]]
(C++17)
|
表示从前一个 case 标签直落的行为是故意的,不应被会对直落发出警告的编译器诊断
(属性说明符) |
|
C 文档
关于
break
|
|