Whenever a case
is ended in a switch
, the code of the next case will get executed. This last one can be prevented by using the ´break` statement.
As this so-called fallthrough behavior can introduce bugs when not intended, several compilers and static analyzers give a warning on this.
From C++17 on, a standard attribute was introduced to indicate that the warning is not needed when the code is meant to fall through.
Compilers can safely give warnings when a case is ended without break
or [[fallthrough]]
and has at least one statement.
switch(input) {
case 2011:
case 2014:
case 2017:
std::cout << "Using modern C++" << std::endl;
[[fallthrough]]; // > No warning
case 1998:
case 2003:
standard = input;
}
See the proposal for more detailed examples on how [[fallthrough]]
can be used.