• Expressions are the fundamental means of specifying computations in a programming language • To understand expression evaluation, need to be familiar with the following concepts: – The
Trang 1Chapter 7
Data Type Expressions
and
Assignment Statements
ISBN 0-321-33025-0
Chapter 7 Topics
• Introduction
• Arithmetic Expressions
• Overloaded Operators
• Type Conversions
• Relational and Boolean Expressions
• Short-Circuit Evaluation
• Assignment Statements
Trang 2• Expressions are the fundamental means of
specifying computations in a programming
language
• To understand expression evaluation, need to
be familiar with the following concepts:
– The orders of operator and operand evaluation
– Type mismatch
– Coercion
• Essence of imperative languages is dominant
Copyright © 2006 Addison-Wesley All rights reserved 1-3
role of assignment statements
Arithmetic Expressions
• Their evaluation was one of the motivations for
• Their evaluation was one of the motivations for the development of the first programming
languages
• Arithmetic expressions consist of operators, operands, parentheses, and function calls
Trang 3Arithmetic Expressions – Design issues
• What are the operator precedence rules?
• What are the operator associativity rules?
• What is the order of operand evaluation?
• Are there restrictions on operand evaluation side effects?
• Does the language allow user-defined operator overloading?
• What mode mixing is allowed in expressions?
Copyright © 2006 Addison-Wesley All rights reserved 1-5
Arithmetic Expressions - Operators
• AA ternaryternary operator has three operandsoperator has three operands
Trang 4Arithmetic Expressions –
Operator Precedence
Operator Precedence
• The operator precedence rules for expression evaluation define the order in which “adjacent”
evaluation define the order in which adjacent operators of different precedence levels are
evaluated
– “Adjacent” means they are separated by at most one operand
Typical precedence levels
• Typical precedence levels
1 Parentheses
2 Unary operators
3 ** (exponentiation, if the language supports it)
4 *, /
Copyright © 2006 Addison-Wesley All rights reserved 1-7
5 +,
-Arithmetic Expressions – Operator
Associativity
• The operator associativity rules for expression evaluation define the order in which adjacent
evaluation define the order in which adjacent
operators with the same precedence level are
evaluated
• Typical associativity rules:
– Left to right, except **, which is right to left g p g
– Example: In FORTRAN
A**B**C A**(B**C)
• APL: all operators have equal precedence and all operators associate right to left
• Precedence and associativity rules can be
overriden with parentheses
Trang 5Operand evaluation order
• Variables in expressions are evaluated by
fetching their values from memory
• If an operand is a parenthesized expression,If an operand is a parenthesized expression,
then all operators it contains must be evaluated before its value can be used as an operand
before its value can be used as an operand
• If neither of the operands of an operator has
irrelevant
Copyright © 2006 Addison-Wesley All rights reserved 1-9
Functional side effects
• A side effect of a function occurs when the
function changes either one of its two-way
parameters or a nonlocal variable
• The problem with functional side effects:
– When a function referenced in an expression When a function referenced in an expression
alters another operand of the expression
Trang 6b = a + fun(a);
…
int fun1() {
a = 17;
int fun(int &a) {
int b = a / 2;
2
return 3;
}
id f 2()
a *= 2;
return b;
}
void fun2() {
a = a + fun1(); }
void main() { fun2();
Copyright © 2006 Addison-Wesley All rights reserved 1-11
();
}
Functional side effects - Solutions
1 Write the language definition to disallow
functional side effects
– No two-way parameters in functions
– No nonlocal references in functions
– Advantage: it works!
– Disadvantage: Programmers want the flexibility of two-way parameters and nonlocal references
2 Write the language definition to demand that operand evaluation order be fixed
– Disadvantage: limits some compiler optimizations
Trang 7Overloaded Operators
• Use of an operator for more than one purpose is called operator overloading
called operator overloading
• Some are common (e.g., + for int and float)
• Some are potential trouble (e.g., * in C/C++)p ( g , / )
– Loss of compiler error detection (omission of an
operand should be a detectable error)
Readability may suffer even when the operators make
– Readability may suffer, even when the operators make sense
A * B + C * D >< MatAdd(MatMult(A, B), MatMult(C, D))
but nothing prevents a user from defining + to mean addition
of elements in array
• Can be avoided by introduction of new symbols
Copyright © 2006 Addison-Wesley All rights reserved 1-13
Can be avoided by introduction of new symbols
(e.g., Pascal’s div)
Type Conversions
object to a type that cannot include all of the
values of the original type, e.g., float to int
is converted to a type that can include at least approximations to all of the values of the
original type, e.g., int to float
Trang 8Coercion in Expressions
operands of different types
– Disadvantage: They decrease in the type error
detection ability of the compiler
• In most languages, all numeric types are coerced
in expressions, using widening conversions
• In Ada, there are virtually no coercions in
expressions
Copyright © 2006 Addison-Wesley All rights reserved 1-15
expressions
Explicit Type Conversion - Cast
• Most languages provide some capability for
doing explicit conversions, both widening and narrowing
• In some cases, warning messages are produced
when an explicit narrowing conversion results in
a significant change to the value of the object being converted
Trang 9Relational and Boolean Expressions
• Relational Expressions
– Use relational operators and operands of various types
– Operator symbols used vary somewhat among
languages (!=, /=, NE., <>, #)
• Boolean Expressions
– Boolean expressions consist of Boolean variables, p , Boolean constants, relational expressions, and Boolean operators
Copyright © 2006 Addison-Wesley All rights reserved 1-17
Short-Circuit Evaluation
one in which the result is determined without evaluating all of the operands and/or operators
evaluating all of the operands and/or operators
• Example:
index = 1;
while (index < listlen) && (list[index] != key) index++;
Trang 10Short Circuit Evaluation - Languages
• C, C++, and Java: use short-circuit evaluation
for the usual Boolean operators (&& and ||), but
also provide bitwise Boolean operators that are
also provide bitwise Boolean operators that are
not short circuit (& and |)
• Short-circuit evaluation exposes the potential problem of side effects in expressions
e.g (a > b) || (b++ / 3)
Copyright © 2006 Addison-Wesley All rights reserved 1-19
Short Circuit Evaluation - Languages
• Ada: programmer can specify either
(short-circuit is specified with and then and or else)
INDEX := 1;
while (INDEX <= LISTLEN) and then
(LIST(INDEX) /= KEY) loop
INDEX := INDEX + 1;
end loop;
…
answer : BOOLEAN;
answer := (a > b) or else (b++ / 3);
Trang 11Assignment Statements
• The assignment statement is one of the central constructs in imperative languages
• It provides the mechanism by which the user can
• It provides the mechanism by which the user can dynamically change the bindings of values to
i bl
variables
Copyright © 2006 Addison-Wesley All rights reserved 1-21
Simple Assignments
• <target_var> <assignment_op> <expr>
• The operator symbol:
FORTRAN BASIC PL/I C C++ Java: ‘=’
– FORTRAN, BASIC, PL/I, C, C++, Java: =
– ALGOLs, Pascal, Ada: ‘:=’
• ‘=‘ can be bad if it is overloaded for the
relational operator for equality
e.g (PL/I) A = B = C;
Trang 12More complicated assignments
• Multiple targets (PL/I)
A, B = 10
• Conditional targets (C, C++, and Java)
(first == true) ? total : subtotal = 0
• Compound assignment operators (C/C++, Java)
sum += next;
• C, C++, and Java treat = as an arithmetic binary
t
operator
a = b * (c = d * 2 + 1) + 1
b + ( d / b++) 1 (side effect)
Copyright © 2006 Addison-Wesley All rights reserved 1-23
a = b + (c = d / b++) – 1; (side effect)
More complicated assignments (cont.)
• Assignment as an Expression
– In C, C++, and Java, the assignment statement produces a result
p
– So, they can be used as operands in expressions e.g.
while ((ch = getchar())!= EOF) {
…
}
Trang 13Mixed-Mode Assignment
• In FORTRAN, C/C++, any numeric value can be
assigned to any numeric scalar variable;
whatever conversion is necessary is done
• In Pascal, integers can be assigned to reals, but reals cannot be assigned to integers (the user
must specify whether the conversion from real
to integer is truncated or rounded)
• In Java, only widening assignment coercions are done
Copyright © 2006 Addison-Wesley All rights reserved 1-25
• In Ada, there is no assignment coercion