Short-circuit Evaluation

Definition

A boolean expression that is known to be true or false without being completely evaluated is short-circuited at the earliest possible point. The parts that don't need to be evaluated are not evaluated.

Explanation

When boolean expressions are joined by "&&", if the left-sided boolean expression is false, the entire expression must also be false, regardless of whether or not the rest of expression is true or false.

Similarly, when boolean expressions are joined by "||", if the left-sided boolean expression is true, the entire expression must also be true, regardless of whether or not the rest of the expression is true or false.

Short-circuit evaluation is able to determine the final value of the expression without evaluating the entire expression, hence its name.

Examples

Example One

boolean a = false;
boolean b = true;
return(a && b);

Without evaluating b, this will return false because a is false.

Example Two

boolean a = true;
boolean b = false;
return(a || b);

Without evaluating b, this will return true because a is true.

Practical Example

We'll say that a positive int divides itself if every digit in the number divides into the number evenly. So for example 148 divides itself since 1, 4, and 8 all divide into 148 evenly. We'll say that 0 does not divide into anything evenly, so no number with a 0 digit divides itself.1

A program, which checks to see whether or not a number divides itself, may look like:

public static boolean dividesSelf(int num) {
  int hold = num,
      digit;
  while(hold != 0){
    digit = hold % 10;
    if((num % digit) != 0 || (digit == 0) ){
      break;
    }
    hold /= 10;
  }
  return(hold == 0); 
}

In cases where num includes a 0 digit, this program would crash before returning an answer. For example, with the number 308, during the second iteration of the while loop, the program is terminated because num is divided by zero on line 6. But isn't the possibility that digit is zero already taken care of with the second part of the if condition? No. The program evaluates (num % digit) before the value of digit. So in a sense, this is a Short-circuit error.

To fix this, switch around the conditions of the if statement:

if((digit == 0) || (num % digit) != 0){

Now, if digit is zero the condition is evaluated to be true without looking at the second part. The error is now avoided.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License