Professional Documents
Culture Documents
Expressions and
Assignment
Statements
ISBN 0-321-33025-0
Evaluation of Variables and Constants
1-2
Evaluation of Parenthesized Expression
1-3
Side Effects and Evaluation Order
1-4
Side Effects
1-5
Example – without Side Effects
a + fun (a)
1-6
Example – with Side Effects
a + fun (a)
1-7
Assumption
1-8
Different Evaluation Orders Create
Different Results
• If the value of a is fetched first (in the
expression evaluation process), its value is
10 and the value of the expression is 20.
1-9
Example
int a = 5;
int fun1()
{
a = 17 ;
return 3;
} /* end of fun1 */
void main()
{
a = a + fun1();
} /* end of main */
1-11
Operator Overloading
1-12
Ampersand (&) in C
1-13
Possible Dangers of Overloading
1-14
Short-Circuit Evaluation
1-15
Short-Circuit Evaluation
1-16
Example
• For example,
– the value of the arithmetic expression
(3 * a) * (b / 13 - 1) is independent of
the value of (b / 13 - l) if a is 0, because
0 * x = 0 for any x.
– So when a is 0, there is no need to evaluate
• (b / 13 - l)
or
• perform the second multiplication.
• However, in arithmetic expressions this
shortcut is not easily detected during
execution, so it is NEVER taken.
1-17
Another Example
index = 0;
while ((index < listlen) && (list[index] != key))
index = index +1 ;
1-20
Short-Circuit Evaluation May Result in
Errors
• Short-circuit evaluation of expressions exposes
the problem of allowing side effects in expressions.
• Suppose that
– short-circuit evaluation is used on an expression
and
– part of the expression that contains a side effect is not
evaluated
then the side effect will only occur in complete
evaluations of the whole expression.
• If program correctness depends on the side effect,
short-circuit evaluation can result in a serious
error.
1-21
Example
1-22