命名空间
变体
操作

break 语句

来自 cppreference.cn
< cpp‎ | language
 
 
C++ 语言
 
 

导致外围的 forrange-forwhiledo-while 循环或 switch 语句终止。

当使用条件表达式和条件语句以其他方式终止循环很笨拙时使用。

目录

[编辑] 语法

attr (可选) break ;
attr - (C++11 起) 任意数量的 属性

[编辑] 解释

仅出现在循环体(whiledo-whilefor)的 statementswitchstatement 内。在此语句之后,控制权转移到紧跟外围循环或 switch 的语句。与任何块退出一样,在外围复合语句或循环/switch 的 condition 中声明的所有自动存储对象都会在执行外围循环后的第一行之前被销毁,销毁顺序与构造顺序相反。

[编辑] 注解

break 语句不能用于跳出多个嵌套循环。 goto 语句 可以用于此目的。

[编辑] 关键字

break

[编辑] 示例

#include <iostream>
 
int main()
{
    int i = 2;
    switch (i)
    {
        case 1: std::cout << "1";   // <---- maybe warning: fall through
        case 2: std::cout << "2";   // execution starts at this case label (+warning)
        case 3: std::cout << "3";   // <---- maybe warning: fall through
        case 4:                     // <---- maybe warning: fall through
        case 5: std::cout << "45";  //
                break;              // execution of subsequent statements is terminated
        case 6: std::cout << "6";
    }
    std::cout << '\n';
 
    for (char c = 'a'; c < 'c'; c++)
    {
        for (int i = 0; i < 5; i++)      // only this loop is affected by break
        {                                //
            if (i == 2)                  //
                break;                   //
            std::cout << c << i << ' ';  //
        }
    }
    std::cout << '\n';
}

可能的输出

2345
a0 a1 b0 b1

[编辑] 参见

(C++17)
指示从前一个 case 标签的 fall through 是有意的,并且不应被编译器诊断为 fall-through 警告
(属性说明符)[编辑]
C 文档 关于 break