Concepts of Programming Languages

(Sean Pound) #1

352 Chapter 8 Statement-Level Control Structures


The crux of the problem in this example is that the else clause follows two
then clauses with no intervening else clause, and there is no syntactic indicator
to specify a matching of the else clause to one of the then clauses. In Java, as in
many other imperative languages, the static semantics of the language specify
that the else clause is always paired with the nearest previous unpaired then
clause. A static semantics rule, rather than a syntactic entity, is used to provide
the disambiguation. So, in the example, the else clause would be paired with the
second then clause. The disadvantage of using a rule rather than some syntactic
entity is that although the programmer may have meant the else clause to be the
alternative to the first then clause and the compiler found the structure syntac-
tically correct, its semantics is the opposite. To force the alternative semantics
in Java, the inner if is put in a compound, as in

if (sum == 0) {
if (count == 0)
result = 0;
}
else
result = 1;

C, C++, and C# have the same problem as Java with selection statement
nesting. Because Perl requires that all then and else clauses be compound, it
does not. In Perl, the previous code would be written as

if (sum == 0) {
if (count == 0) {
result = 0;
}
} else {
result = 1;
}

If the alternative semantics were needed, it would be

if (sum == 0) {
if (count == 0) {
result = 0;
}
else {
result = 1;
}
}

Another way to avoid the issue of nested selection statements is to use an
alternative means of forming compound statements. Consider the syntactic
structure of the Java if statement. The then clause follows the control expres-
sion and the else clause is introduced by the reserved word else. When the
Free download pdf