Concepts of Programming Languages

(Sean Pound) #1

336 Chapter 7 Expressions and Assignment Statements


A language that provides short-circuit evaluations of Boolean expressions
and also has side effects in expressions allows subtle errors to occur. Suppose
that short-circuit evaluation is used on an expression and part of the expres-
sion that contains a side effect is not evaluated; then the side effect will occur
only in complete evaluations of the whole expression. If program correctness
depends on the side effect, short-circuit evaluation can result in a serious error.
For example, consider the Java expression

(a > b) || ((b++) / 3)

In this expression, b is changed (in the second arithmetic expression) only
when a <= b. If the programmer assumed b would be changed every time
this expression is evaluated during execution (and the program’s correctness
depends on it), the program will fail.
Ada allows the programmer to specify short-circuit evaluation of the Bool-
ean operators AND and OR by using the two-word operators and then and
or else. Ada also has non–short-circuit operators, and and or.
In the C-based languages, the usual AND and OR operators, && and ||,
respectively, are short-circuit. However, these languages also have bitwise AND
and OR operators, & and |, respectively, that can be used on Boolean-valued
operands and are not short-circuit. Of course, the bitwise operators are only
equivalent to the usual Boolean operators if all operands are restricted to being
either 0 (for false) or 1 (for true).
All of the logical operators of Ruby, Perl, ML, F#, and Python are short-
circuit evaluated.
The inclusion of both short-circuit and ordinary operators in Ada is
clearly the best design, because it provides the programmer the flexibility of
choosing short-circuit evaluation for any Boolean expression for which it is
appropriate.

7.7 Assignment Statements


As we have previously stated, the assignment statement is one of the central
constructs in imperative languages. It provides the mechanism by which the
user can dynamically change the bindings of values to variables. In the follow-
ing section, the simplest form of assignment is discussed. Subsequent sections
describe a variety of alternatives.

7.7.1 Simple Assignments


Nearly all programming languages currently being used use the equal sign for
the assignment operator. All of these must use something different from an
equal sign for the equality relational operator to avoid confusion with their
assignment operator.
Free download pdf