You may wonder why we need identifiers for both the start and end of each of the cases. The reason is that the code to be run when for a given case does not automatically stop at the point where the next case starts. It always continues through to the next break statement.
This allows us to simplify our processing where we want to perform the same processing for two or more cases. We can list each of these case statements one after the other with no code in between. The code that all of them will run follows after the last case. The end of the code is identified by a single break statement.
case 1: case 2: case 3: answer = "value is 1, 2, or 3"; break; case 4: . . .
You should always group your code together like this so that each time that you have code within the switch statement that is followed by another case that the code ends with a break statement to stop it falling through.
There may be rare situations where code can be made far more efficient by actually allowing the code to fall through past case labels. Unless doing so provides major efficiency improvements to the code, the additional maintenance issues that such code can cause will outweigh the benefits that could be gained. If you do have a situation where you want to allow code to fall through then you should make it very clear in your code that this action is deliberate and that it is not simply that a break statement has been accidentally left out.
What We Have Learnt
This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.