C++ 属性:fallthrough (C++17 起)
来自 cppreference.cn
指示从前一个 case 标签的贯穿是故意的,并且不应被警告贯穿的编译器诊断。
目录 |
[编辑] 语法
[[fallthrough]]
|
|||||||||
[编辑] 解释
只能应用于空语句以创建贯穿语句 ([[fallthrough]];)。
贯穿语句只能在switch语句中使用,其中要执行的下一个语句是带有该 switch 语句的 case 或 default 标签的语句。如果贯穿语句在循环内部,则下一个(带标签的)语句必须是该循环的同一迭代的一部分。
[编辑] 示例
运行此代码
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++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
CWG 2406 | C++17 | [[fallthrough]] 可能出现在循环中 嵌套在目标 switch 语句中 |
已禁止 |
[编辑] 参考
- C++23 标准 (ISO/IEC 14882:2024)
- 9.12.6 Fallthrough attribute [dcl.attr.fallthrough]
- C++20 标准 (ISO/IEC 14882:2020)
- 9.12.5 Fallthrough attribute [dcl.attr.fallthrough]
- C++17 标准 (ISO/IEC 14882:2017)
- 10.6.5 Fallthrough attribute [dcl.attr.fallthrough]
[编辑] 另请参阅
C 文档 for fallthrough
|