Share via


編譯器警告 (層級 1,錯誤,關閉) C5262

隱含的落入會發生在這裡;您缺少 break 語句嗎? [[fallthrough]]在案例之間刻意省略語句時 break 使用

備註

在 switch 語句案例之間隱含落的控制流程,是 C 和 C++ 的 Bug 歷史來源。 雖然我們有 __fallthrough SAL 宏,但它不適用於建置編譯器診斷。 由於客戶有舊版程式碼,因此若沒有某種方式表示刻意發生,便無法提供可採取動作的警告。 在 C++17 中 [[fallthrough]] ,已新增 屬性以指出這類實例。 編譯器可以將此屬性納入考慮,並隱藏新的警告。

編譯器警告 C5262 是 Visual Studio 2022 17.4 版的新功能,而且預設為關閉,並在啟用時預設視為錯誤。 若要在不中斷建置的情況下繼續支援舊版程式碼,必須明確啟用 C5262。 如需如何啟用此警告的詳細資訊,請參閱 預設 關閉的編譯器警告。

範例

範例程式碼會針對沒有 break 或 語句或 [[fallthrough]]return 屬性的案例顯示診斷 switch

// C5262.cpp
// compile using /std:c++17 /we5262

int main(int argc, char** argv)
{
    switch (argc)
    {
        case 0: ++argv;
        case 1:
        case 2: argv++;
        default:
            argv = 0;
    }
}

/*
When built, the compiler produces this output:

.\C5262.cpp(9,9): error C5262: implicit fall-through occurs here; are you missing a break statement? Use [[fallthrough]] when a break statement is intentionally omitted between cases
        case 1:
        ^
.\C5262.cpp(8,17): note: statement that may fall through is here
        case 0: ++argv;
                ^
.\C5262.cpp(11,9): error C5262: implicit fall-through occurs here; are you missing a break statement? Use [[fallthrough]] when a break statement is intentionally omitted between cases
        default:
        ^
.\C5262.cpp(10,17): note: statement that may fall through is here
        case 2: argv++;
*/

若要在刻意設計案例之間的控制流程時解決此問題,請使用 [[fallthrough]] 屬性。

另請參閱

switch statement (C++)
[[fallthrough]] 屬性