C++ 屬性:fallthrough (C++17 起)
來自 cppreference.com
指示從前一個 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
|