In switch case statement, we need to use break statement to discontinue the execution of other cases beneath. This is called fallthrough that happens.
Some compiler shows fallthrough warning that we can disable using [[fallthrough]] attribute. We can use [[fallthrough]] attribute with null statement to let compiler know that this fallthrough is intentional.
#include "../helpers/stdout.h"
int main(int argc, char const *argv[])
{
int value{1};
switch (value)
{
case 1:
print("Case 1");
[[fallthrough]];
case 2:
print("Case 2");
[[fallthrough]];
default:
print("default case");
}
return 0;
}If we do not use [[fallthrough]] attribute, compiling this program gives following error.
❯ g++-15 -ggdb -std=c++20 -Wimplicit-fallthrough fallthrough.cpp ../helpers/stdout.cpp -o fallthrough.o
ut
fallthrough.cpp: In function 'int main(int, const char**)':
fallthrough.cpp:10:14: warning: this statement may fall through [-Wimplicit-fallthrough=]
10 | print("Case 1");
| ~~~~~^~~~~~~~~~
fallthrough.cpp:12:5: note: here
12 | case 2:
| ^~~~