CSADPRG_mod4_short_circuit_evaluation
original file
this is unedited
short circuit evaluation
- ... of an expression happens when the result is determined w/o evaluating all of the operands and/or operators
- example:
(13 * a) * (b / 13 - 1)
the value of the expression is independent of (b / 13 - 1) if a is 0 , because 0 * x = 0 for any x. This shortcut however, is difficult to detect during execution.
(a >= 0) && (b < 10)
- the value of the expression is independent of the second relational expression if
a<0
because the expression becomes false agad - if
a < 0
there's no need to evaluate b, the constant, the second relational expression, or the && operator
Let's look at a potential problem with non-short-circuit evaluation. Suppose Java did not use short-circuit evaluation, consider the following code for a table lookup. list which has listlen elements is the array to be searched and key is the value we are looking for.
index = 0;
while ((index < listlen) && (list[index] != key))
index = index + 1;
- If it does not short-circuit both relational expressions will be evaluated regardless of the value of thee first one, so if
index == listlen
, it will reference list[listlen] which will cause an error because the size of the array islistlen
so the last index should belistlen - 1
.
On the other hand, short-circuit evaluation exposes the potential problem of side-effects in expressions. Consider this Java expression
(a > b) || ((b++) / 3)
- b is only changed if a <= b , thus the programmer cannot assume that b would be changed every time this expression is evaluated during execution.
In the C-based languages, l AND and OR operators, && and ||
, 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.