Namespaces
Variants

break statement

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
continue - break
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
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 statement を終了させます。

条件式と条件文を使用してループを終了することが不適切な場合に使用されます。

目次

構文

attr  (オプション) break ;
attr - (C++11以降) 任意の数の 属性

説明

ループ本体( while do-while for )の statement 内、または switch statement 内でのみ現れます。 この文の後、制御は外側のループまたはswitchの直後の文に移ります。すべてのブロック終了と同様に、外側の複合文またはループ/switchの condition 内で宣言されたすべての自動記憶域オブジェクトは、外側のループに続く最初の行が実行される前に、構築の逆順で破棄されます。

注記

複数のネストされたループから抜け出すためにbreak文を使用することはできません。この目的には goto文 を使用することができます。

キーワード

break

#include <iostream>
int main()
{
    int i = 2;
    switch (i)
    {
        case 1: std::cout << "1";   // <---- 警告の可能性: フォールスルー
        case 2: std::cout << "2";   // このケースラベルから実行開始 (+警告)
        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

関連項目

(C++17)
前のcaseラベルからのフォールスルーが意図的であり、フォールスルーについて警告するコンパイラによって診断されるべきではないことを示す
(属性指定子)