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:

    If English is spoken in heaven ... God undoubtedly employs Cranmer as his speechwriter. The angels of the lesser ministries probably use the language of the New English Bible and the Alternative Service Book for internal memos.
    Charles, Prince Of Wales (b. 1948)

    If you have abandoned one faith, do not abandon all faith. There is always an alternative to the faith we lose. Or is it the same faith under another mask?
    Graham Greene (1904–1991)