Επεξεργασία

Κοινή χρήση μέσω


Compiler warning (level 1, error, off) C5262

implicit fall-through occurs here; are you missing a break statement? Use [[fallthrough]] when a break statement is intentionally omitted between cases

Remarks

Control flow that implicitly falls between cases of switch statements is a historical source of bugs for both C and C++. While we had the __fallthrough SAL macro, it wasn't useful for the build-compiler diagnostics. Since customers have legacy code that "falls through" on purpose, it isn't viable to give an actionable warning without some way of indicating an intentional fall through. In C++17, the [[fallthrough]] attribute was added to indicate such an instance. The compiler can take this attribute into account and suppress the new warning.

Compiler warning C5262 is new in Visual Studio 2022 version 17.4, and is both off by default and treated as an error by default when enabled. To continue to support legacy code without build breaks, C5262 must be explicitly enabled. For more information on how to enable this warning, see Compiler warnings that are off by default.

Example

The sample code shows diagnostics for switch cases that fall through without break or return statements or the [[fallthrough]] attribute.

// 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++;
*/

To resolve this issue when the control flow between cases is intentional, use the [[fallthrough]] attribute.

See also

switch statement (C++)
[[fallthrough]] attribute