How to use __attribute__((fallthrough)) correctly in gcc
Solution 1
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;
}
Solution 2
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...
M.M
Professional C programmer for 21 years, mostly on embedded systems. Some Windows C++ development also.
Updated on June 24, 2022Comments
-
M.M almost 2 years
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?