How to use __attribute__((fallthrough)) correctly in gcc

20.5k Views Asked by At

Code sample:

int main(int argc, char **argv)
{
    switch(argc)
    {
    case 0:
        argc = 5;
        __attribute__((fallthrough));

    case 1:
        break;
    }
}

Using gcc 6.3.0, with -std=c11 only, this code gives a warning:

<source>: In function 'main':
7 : <source>:7:3: warning: empty declaration
   __attribute__((fallthrough));
   ^~~~~~~~~~~~~

What is the correct way to use this without eliciting a warning?

3

There are 3 best solutions below

4
On BEST ANSWER

As previously answered, __attribute__ ((fallthrough)) was introduced in GCC 7. To maintain backward compatibility and clear the fall through warning for both Clang and GCC, you can use the /* fall through */ marker comment.

Applied to your code sample:

int main(int argc, char **argv)
{
    switch(argc)
    {
    case 0:
        argc = 5;
        /* fall through */

    case 1:
        break;
    }

    return 0;
}
0
On

You can also try the code below, because only this one works for me on Android:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
// your code
#pragma GCC diagnostic pop
4
On

Tried to comment previous, but did not have 50 reputation.

So, my experiences:

1) the feature is since gcc 7, so using attribute on older compilers will give warning. therefore I currently use:

#if defined(__GNUC__) && __GNUC__ >= 7
 #define FALL_THROUGH __attribute__ ((fallthrough))
#else
 #define FALL_THROUGH ((void)0)
#endif /* __GNUC__ >= 7 */

and then I use FALL_THROUGH; in code

(Some day I figure out what is needed for clang, but not today)

2) I spent considerable time to try to get the gcc marker comment to work, but nothing I tried worked! Some comment somewere suggested that in order for that to work one has to add -C to gcc arguments (meaning comments will be passed to cc1). Sure gcc 7 documentation doesn't mention anything about this requirement...