Loading lessons...
Switch Fallthrough and Scoping
Switch Fallthrough and Scoping
Two subtle switch behaviors that trip up beginners: fallthrough and case scope.
Fallthrough: running the next case by accident
A case normally ends with break. If you forget it, execution keeps going straight into the next case, regardless of its value. That is fallthrough.
switch (x) {
case 1:
cout << "one";
// no break here
case 2:
cout << "two";
break;
}
If x is 1, this prints "onetwo", because with no break at the end of case 1, execution falls through into case 2.
Accidental vs actual intentional
Most of the time fallthrough is a mistake: you simply forgot the break. If fallthrough is truly what you want, mark it explicitly with the C++17 attribute [[fallthrough]]:
case 1:
cout << "one";
[[fallthrough]];
case 2:
cout << "two";
break;
The attribute tells readers and compilers: this skip is intentional.
Variables and case scope
All the cases share one block as far as variables go. A variable declared in a case can jump into the next case too, which can cause confusion. LearnCpp 8.6 suggests wrapping a case body in curly braces { } to give it its own scope:
case 1: {
string msg = "One";
cout << msg << endl;
break;
}
case 2:
// msg is not declared here
break;
TL;DR
- Missing
breakmakes the case fall through into the next one. - Mark intentional fallthrough with
[[fallthrough]](C++17). - A variable declared in a case belongs to the whole switch scope.
- Use
{ }inside a case to limit where the variable lives.