Concepts of Programming Languages

(Sean Pound) #1

358 Chapter 8 Statement-Level Control Structures


evaluated. The only version of Ruby’s case expressions that is described here is
semantically similar to a list of nested if statements:

case
when Boolean_expression then expression

...
when Boolean_expression then expression
[else expression]
end


The semantics of this case expression is that the Boolean expressions are
evaluated one at a time, top to bottom. The value of the case expression is the
value of the first then expression whose Boolean expression is true. The else
represents true in this statement, and the else clause is optional. For
example,^4

leap = case
when year % 400 == 0 then true
when year % 100 == 0 then false
else year % 4 == 0
end

This case expression evaluates to true if year is a leap year.
The other Ruby case expression form is similar to the switch of Java. Perl,
Python, and Lua do not have multiple-selection statements.

8.2.2.3 Implementing Multiple Selection Structures
A multiple selection statement is essentially an n-way branch to segments of
code, where n is the number of selectable segments. Implementing such a state-
ment must be done with multiple conditional branch instructions. Consider
again the general form of the C switch statement, with breaks:

switch (expression) {
case constant_expression 1 : statement 1 ;
break;

...
case constantn: statementn;
break;
[default: statementn+ 1 ]
}
4. This example is from Thomas et al. (2005).

Free download pdf