Concepts of Programming Languages

(Sean Pound) #1
8.2 Selection Statements 357

case 2: case 3: case 5: case 7:
process_prime(x);
else
case 4: case 6: case 8: case 9: case 10:
process_composite(x);

This code may appear to have diabolically complex form, but it was designed
for a real problem and works correctly and efficiently to solve that problem.^3
The Java switch prevents this sort of complexity by disallowing case
expressions from appearing anywhere except the top level of the body of the
switch.
The C# switch statement differs from that of its C-based predecessors
in two ways. First, C# has a static semantics rule that disallows the implicit
execution of more than one segment. The rule is that every selectable segment
must end with an explicit unconditional branch statement: either a break,
which transfers control out of the switch statement, or a goto, which can
transfer control to one of the selectable segments (or virtually anywhere else).
For example,

switch (value) {
case -1:
Negatives++;
break;
case 0:
Zeros++;
goto case 1;
case 1:
Positives++;
default:
Console.WriteLine("Error in switch \n");
}

Note that Console.WriteLine is the method for displaying strings in C#.
The other way C#’s switch differs from that of its predecessors is that the
control expression and the case statements can be strings in C#.
PHP’s switch uses the syntax of C’s switch but allows more type flex-
ibility. The case values can be any of the PHP scalar types—string, integer, or
double precision. As with C, if there is no break at the end of the selected
segment, execution continues into the next segment.
Ruby has two forms of multiple-selection constructs, both of which are
called case expressions and both of which yield the value of the last expression


  1. The problem is to call process_prime when x is prime and process_composite
    when x is not prime. The design of the switch body resulted from an attempt to optimize
    based on the knowledge that x was most often in the range of 1 to 10.

Free download pdf