A switch statement evaluates its control expression and then jumps to the case statement whose value matches the control expression:
switch (controlExp) { case value1: exp1; break; case value2: exp2; break; case value3: exp3; break; ... default: exp4; break; }
If none of the case statements match the control value, the default statement executes. The default statement is optional and can be placed anywhere in the sequence of case statements.
If you want more than one case statement to execute the same block of code, put the case statements right after each other. For example, if you wanted switch on both "a" and "A":
switch ($letter) { case "a": case "A": print("Apple\n"); // Executed if "a" or "A" break; case "b": case "B": print("Banana\n"); // Executed if "b" or "B" break; }
For historical compatibility with other languages, MEL’s switch statement includes a bit of strange behavior: if you don’t add a break statement at the end of the expressions under a case statement, MEL will continue to evaluate the other expressions in the switch block until it reaches a break statement or the end of the block. This is known as fall-through.
For example, consider this switch statement:
switch ($color){ case "GREEN": do_green(); break; case "PINK": do_pink(); case "RED": do_red(); break; default: do_blue(); break; }
In this statement, if $color is "PINK", the switch statement will jump to case "PINK": and execute do_pink(). What you might not expect is that because there is no break statement after that, execution will fall through and execute do_red() as well!
Fall-through is error-prone and almost never useful. Watch out for it. Unless you are familiar with the switch statement from another language, it is usually a better idea to use an if...else if...else statement instead:
if ($color == "GREEN") { do_green(); } else if ($color == "PINK") { do_pink(); } else if ($color == "RED") { do_red(); } else { do_blue(); }
If you actually want to use fall-through as a feature, it is helpful to point out that you are doing so in a comment so anyone looking at your code doesn’t just assume it’s an error:
switch ($color){ case "GREEN": do_green(); break; case "PINK": do_pink(); // FALL THROUGH case "RED": do_red(); ...
Although the last case in a switch statement does not need a break statement since the switch is at its end, it is still a good idea to add the break statement. If you add more cases to the switch statement, the break statement is already there.
Except where otherwise noted, this work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License