Side Effects Short Circuit Arithmetic Expressions Potentials for

  • Slides: 5
Download presentation
Side Effects & Short Circuit

Side Effects & Short Circuit

Arithmetic Expressions: Potentials for Side Effects • Functional side effects: when a function changes

Arithmetic Expressions: Potentials for Side Effects • Functional side effects: when a function changes a two-way parameter (call by reference) or a non-local variable • Problem with functional side effects: • When a function referenced in an expression alters another operand of the expression; e. g. , for a parameter change: a = 10; int fun(x int){ x=x+1; return x+20; } b = fun(&a)+ a; System. out. print(b); RIGHT => LEFT a=10 b= fun(10) +10 b= ? + 10 x=10+1=11 return 11+20=31 b=31+10=41 LEFT => RIGHT fun(10) x=10+1=11 return 11+20=31 b=31+ a b=31+11=42 Java requires that operands appear to be evaluated in left-to-right order 1 -2

Arithmetic Expressions: Potentials for Side Effects Java requires that operands appear to be evaluated

Arithmetic Expressions: Potentials for Side Effects Java requires that operands appear to be evaluated in left-to-right order a = 10; int fun(AAA x){ x=x+1; return x+20; } b = a + fun(a); System. out. print(b); b = a + fun(a); ********** a=10 b=10+fun(10) b=10+ x=10+1=11 return 11+20=31 b=10+31=41 1 -3 b = fun(a)+ a; ********** fun(10) x=10+1=11 return 11+20=31 b=31+ a b=31+11=42

Short Circuit Evaluation • An expression in which the result is determined without evaluating

Short Circuit Evaluation • An expression in which the result is determined without evaluating all of the operands and/or operators • Example: (13*a) * (b/13– 1) If a is zero, there is no need to evaluate (b/13 -1) • Problem with non-short-circuit evaluation index = 1; while (index <= length) && (LIST[index] != value) index++; • When index=length, LIST [index] will cause an indexing problem (assuming LIST has length -1 elements) 1 -4

Short Circuit Evaluation (continued) • C, C++, and Java: use short-circuit evaluation for the

Short Circuit Evaluation (continued) • C, C++, and Java: use short-circuit evaluation for the usual Boolean operators (&& and ||), but also provide bitwise Boolean operators that are not short circuit (& and |) • Short-circuit evaluation exposes the potential problem of side effects in expressions • a=7; b=3; IF (a > b) || (b++ > 3) DO XXXX short-circuit evaluation: STOP, won’t do b++ therefore b=3 • a=7; b=3; IF (a > b) | (b++ > 3) DO XXXX non-short-circuit evaluation: STILL do b++ so b=4; 1 -5