C++ attribute: fallthrough (since C++17)
From cppreference.com
< cpp | language | attributes
Indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fallthrough.
Contents |
[edit]Syntax
[[fallthrough]] | |||||||||
[edit]Explanation
May only be applied to a null statement to create a fallthrough statement ([[fallthrough]];).
A fallthrough statement may only be used in a switch statement, where the next statement to be executed is a statement with a case or default label for that switch statement. If the fallthrough statement is inside a loop, the next (labeled) statement must be part of the same iteration of that loop.
[edit]Example
Run this code
void f(int n){void g(), h(), i(); switch(n){case1:case2: g();[[fallthrough]];case3:// no warning on fallthrough h();case4:// compiler may warn on fallthroughif(n <3){ i();[[fallthrough]];// OK}else{return;}case5:while(false){[[fallthrough]];// ill-formed: next statement is not// part of the same iteration}case6:[[fallthrough]];// ill-formed, no subsequent case or default label}}
[edit]Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
CWG 2406 | C++17 | [[fallthrough]] could appear in a loop nested inside the target switch statement | prohibited |
[edit]References
- C++23 standard (ISO/IEC 14882:2024):
- 9.12.6 Fallthrough attribute [dcl.attr.fallthrough]
- C++20 standard (ISO/IEC 14882:2020):
- 9.12.5 Fallthrough attribute [dcl.attr.fallthrough]
- C++17 standard (ISO/IEC 14882:2017):
- 10.6.5 Fallthrough attribute [dcl.attr.fallthrough]
[edit]See also
C documentation for fallthrough |