Why is GCC warning me about a fallthrough even when I use [[fallthrough]]?

C++Switch StatementC++17Fall Through

C++ Problem Overview


In the following piece of code, I use the standard [[fallthrough]] attribute from C++1z to document that a fallthrough is desired:

#include <iostream>

int main() {
    switch (0) {
        case 0:
            std::cout << "a\n";
            [[fallthrough]]
        case 1:
            std::cout << "b\n";
            break;
    }
}

With GCC 7.1, the code compiles without an error. However, the compiler still warns me about a fallthrough:

warning: this statement may fall through [-Wimplicit-fallthrough=]
    std::cout << "a\n";
    ~~~~~~~~~~^~~~~~~~

Why?

C++ Solutions


Solution 1 - C++

You are missing a semicolon after the attribute:

case 0:
    std::cout << "a\n";
    [[fallthrough]];
    //             ^
case 1:

The [[fallthrough]] attribute is to be applied to an empty statement (see P0188R1). The current Clang trunk gives a helpful error in this case:

error: fallthrough attribute is only allowed on empty statements
    [[fallthrough]]
      ^
note: did you forget ';'?
    [[fallthrough]]
                   ^
                   ;

Update: Cody Gray reported this issue to the GCC team.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questions3rvacView Question on Stackoverflow
Solution 1 - C++s3rvacView Answer on Stackoverflow