C++ 属性: fallthrough (自 C++17 起)
来自 cppreference.cn
< cpp | language | attributes
指示从前一个 case 标签的向下执行是有意的,并且不应被在向下执行时发出警告的编译器诊断。
目录 |
[编辑] 语法
[[fallthrough]]
|
|||||||||
[编辑] 解释
可能只应用于空语句以创建fallthrough 语句 ([[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: // no warning on fallthrough h(); case 4: // compiler may warn on fallthrough if (n < 3) { i(); [[fallthrough]]; // OK } else { return; } case 5: while (false) { [[fallthrough]]; // ill-formed: next statement is not // part of the same iteration } case 6: [[fallthrough]]; // ill-formed, no subsequent case or default label } }
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 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 文档 关于 fallthrough
|