Switch Statement - Alternative Uses

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:

case input when Array: puts 'input is an Array!' when Hash: puts 'input is a Hash!' end

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):

catfood = case when cat.age <= 1: junior when cat.age > 10: senior else normal end

Read more about this topic:  Switch Statement

Famous quotes containing the word alternative:

    Education must, then, be not only a transmission of culture but also a provider of alternative views of the world and a strengthener of the will to explore them.
    Jerome S. Bruner (20th century)

    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)