## Sunday, 28 March 2021

### Short Circuit Evaluation | PPL | Sebesta | Expressions and Assignment Statements

In this post, we will see Short Circuit Evaluation | PPL | Sebesta | Expressions and Assignment Statements | short circuit evaluation, ppl, sebesta, expressions and assignment statements

5. Short Circuit Evaluation

A short-circuit evaluation of an expression is one in which the result is determined without evaluating all of the operands and/or operators.

For example, the value of the arithmetic expression

(13 * a) * (b / 13 - 1)

is independent of the value of (b / 13 - 1) if a is 0 , because 0 * x = 0 for any x . So, when a is 0 , there is no need to evaluate (b / 13 - 1) or perform the second multiplication. However, in arithmetic expressions, this shortcut is not easily detected during execution, so it is never taken.

The value of the Boolean expression

(a >= 0) && (b < 10)

is independent of the second relational expression if a < 0 , because the expression ( FALSE && ( b < 10 )) is FALSE for all values of b .

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 expression 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.

In the C-based languages, the usual AND and OR operators, && and || , respectively, are short-circuit.

Ada allows the programmer to specify short-circuit evaluation of the Boolean 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 .

Watch following video: