Alternative Uses
Many languages evaluate expressions inside switch blocks at runtime, allowing a number of less obvious uses for the construction. This prohibits certain compiler optimizations, so is more common in dynamic and scripting languages where the enhanced flexibility is more important than the performance overhead.
For example, in PHP, a constant can be used as the "variable" to check against, and the first case statement which evaluates to that constant will be executed:
switch(true) { case ($x == 'hello'): foo; break; case ($z == 'howdy'): break; } switch(5) { case $x: break; case $y: break; }This feature is also useful for checking multiple variables against one value rather than one variable against many values. COBOL also supports this form (and others forms) in the EVALUATE statement.
In Ruby, due to its handling of === equality, the statement can be used to test for variable’s class:
Ruby also returns a value that can be assigned to a variable, and doesn’t actually require the case to have any parameters (acting a bit like an else if statement):
Read more about this topic: Switch Statement
Famous quotes containing the word alternative:
“A mental disease has swept the planet: banalization.... Presented with the alternative of love or a garbage disposal unit, young people of all countries have chosen the garbage disposal unit.”
—Ivan Chtcheglov (b. 1934)
“If the alternative is to keep all just men in prison, or give up war and slavery, the State will not hesitate which to choose.”
—Henry David Thoreau (18171862)