Namespaces
Variants

C++ attribute: fallthrough (since C++17)

From cppreference.net
C++ language
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
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
Attributes
(C++23)
(C++11) (until C++26)
(C++14)
fallthrough
(C++17)
(C++20)
(C++17)
(C++11)
(C++20)

前のcaseラベルからのフォールスルーが意図的であり、フォールスルーについて警告するコンパイラによる診断をすべきではないことを示します。

目次

翻訳の説明: - 「Contents」を「目次」に翻訳しました - HTMLタグ、属性、 内のテキスト(Syntax、Explanation、Example、Defect reports、References、See also)はC++関連の専門用語として翻訳せず、原文のまま保持しました - 数値、クラス名、ID、リンク先などはすべて変更せず保持しました - フォーマットと構造は完全に維持しました

構文

[ [ fallthrough ] ]

説明

これは null statement にのみ適用でき、 fallthrough statement ( [ [ fallthrough ] ] ; ) を作成します。

fallthrough文は switch 文内でのみ使用でき、次に実行される文はそのswitch文のcaseまたはdefaultラベルを持つ文でなければなりません。fallthrough文がループ内にある場合、次に実行される(ラベル付き)文はそのループの同じイテレーションの一部である必要があります。

void f(int n)
{
    void g(), h(), i();
    switch (n)
    {
        case 1:
        case 2:
            g();
            [[fallthrough]];
        case 3: // フォールスルーに関する警告なし
            h();
        case 4: // コンパイラはフォールスルーについて警告を発する可能性あり
            if (n < 3)
            {
                i();
                [[fallthrough]]; // OK
            }
            else
            {
                return;
            }
        case 5:
            while (false)
            {
                [[fallthrough]]; // 不正: 次の文は同じ反復処理の一部ではない
            }
        case 6:
            [[fallthrough]]; // 不正、後続のcaseまたはdefaultラベルがない
    }
}

不具合報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
CWG 2406 C++17 [ [ fallthrough ] ] 対象のswitch文内でネストされたループ内に
現れる可能性があった
禁止

参考文献

  • C++23規格 (ISO/IEC 14882:2024):
  • 9.12.6 Fallthrough属性 [dcl.attr.fallthrough]
  • C++20 標準 (ISO/IEC 14882:2020):
  • 9.12.5 Fallthrough 属性 [dcl.attr.fallthrough]
  • C++17規格 (ISO/IEC 14882:2017):
  • 10.6.5 Fallthrough属性 [dcl.attr.fallthrough]

関連項目

C documentation for fallthrough
日本語訳:
C ドキュメント for fallthrough
翻訳内容: - "C documentation" → "C ドキュメント" - "fallthrough" はC++の属性名のため、原文のまま保持 - HTMLタグ、属性、構造は完全に保持 - フォーマットは元のまま維持