Fallthrough
If the code for a given label does not have a break
then it will "fall through"
to the cases below.
This is what makes C-style switches strange. It can occasionaly be useful if the same code should run for some or all cases, but is annoyingly easy to do on accident.1
class Main {
void sayWhoTheyFought(String name) {
switch (name) {
case "Goku":
System.out.println("Fought Pilaf");
System.out.println("Fought The Red Ribbon Army");
case "Gohan": // "Goku" will fall through to this case
System.out.println("Fought Frieza");
System.out.println("Fought Cell");
System.out.println("Fought Majin Buu");
}
}
void main() {
sayWhoTheyFought("Gohan");
System.out.println("----------------------");
sayWhoTheyFought("Goku");
}
}
1
This StackExchange Post explains how this came about. I don't have a primary source on the "The reason that C did it that way is that the creators of C intended switch statements to be easy to optimize into a jump table." claim, but it lines up with my biases and preconceptions. Therefore it must be true!