I came across a case-switch piece of code today and was a bit surprised to see how it worked. The code was:
switch (blah)
{
case a:
break;
case b:
break;
case c:
case d:
case e:
{
/* code here */
}
break;
default :
return;
}
To my surprise in the scenario where the variable was c, the path went inside the “code here” segment. I agree there is no break at the end of the c part of the case switch, but I would have imagined it to go through default instead. When you land at a case blah: line, doesn’t it check if your current value matches the particular case and only then let you in the specific segment? Otherwise what’s the point of having a case?
This is called case fall-through, and is a desirable behavior. It allows you to share code between cases.
An example of how to use case fall-through behavior:
If you enter the switch when
blah == a, then you will executefunction1(),function2(), andfunction3().If you don’t want to have this behavior, you can opt out of it by including
breakstatements.The way a switch statement works is that it will (more or less) execute a
gototo jump to your case label, and keep running from that point. When the execution hits abreak, it leaves the switch block.