Short-circuit evaluation

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the  function evaluates to , the overall value must be  ; and when the first argument of the   function evaluates to  , the overall value must be.

In programming languages with lazy evaluation (Lisp, Perl, Haskell), the usual Boolean operators short-circuit. In others (Ada, Java, Delphi), both short-circuit and standard Boolean operators are available. For some Boolean operations, like exclusive or (XOR), it is impossible to short-circuit, because both operands are always needed to determine a result.

Short-circuit operators are, in effect, control structures rather than simple arithmetic operators, as they are not strict. In imperative language terms (notably C and C++), where side effects are important, short-circuit operators introduce a sequence point: they completely evaluate the first argument, including any side effects, before (optionally) processing the second argument. ALGOL 68 used proceduring to achieve user-defined short-circuit operators and procedures.

The use of short-circuit operators has been criticized as problematic: "The conditional connectives — " cand " and " cor " for short — are ... less innocent than they might seem at first sight. For instance, cor does not distribute over cand : compare
 * (A cand B) cor C with (A cor C) cand (B cor C);

in the case ¬A ∧ C, the second expression requires B to be defined, the first one does not. Because the conditional connectives thus complicate the formal reasoning about programs, they are better avoided."

- Edsger W. Dijkstra

Definition
In any programming language that implements short-circuit evaluation, the expression  is equivalent to the conditional expression , and the expression   is equivalent to. In either case, x is only evaluated once.

The generalized definition above accommodates loosely typed languages that have more than the two truth-values  and , where short-circuit operators may return the last evaluated subexpression. This is called "last value" in the table below. For a strictly-typed language, the expression is simplified to  and   respectively for the boolean case.

Precedence
Although AND takes precedence over OR in many languages, this is not a universal property of short-circuit evaluation. An example of the two operators taking the same precedence and being left-associative with each other is POSIX shell's command-list syntax.

The following simple left-to-right evaluator enforces a precedence of AND over OR by a continue:

function short-circuit-eval (operators, values) let result := True for each (op, val) in (operators, values): if op = "AND" && result = False continue else if op = "OR" && result = True return result else result := val return result

Formalization
Short-circuit logic, with or without side-effects, have been formalized based on Hoare's conditional. A result is that non-short-circuiting operators can be defined out of short-circuit logic to have the same sequence of evaluation.

Support in common programming and scripting languages
As you look at the table below, keep in mind that bitwise operators often do not behave exactly like logical operators, even if both arguments are of,   or Boolean type.

Examples: ,, . , ,.
 * In JavaScript, each of the following 3 expressions evaluates to :
 * In PHP, each of the following 3 expressions evaluates to :

Avoiding undesired side effects of the second argument
Usual example, using a C-based language:

Consider the following example:

In this example, short-circuit evaluation guarantees that  is never called. This is because  evaluates to false. This feature permits two useful programming constructs.


 * 1) If the first sub-expression checks whether an expensive computation is needed and the check evaluates to false, one can eliminate expensive computation in the second argument.
 * 2) It permits a construct where the first expression guarantees a condition without which the second expression may cause a run-time error.

Both are illustrated in the following C snippet where minimal evaluation prevents both null pointer dereference and excess memory fetches:

Idiomatic conditional construct
Since minimal evaluation is part of an operator's semantic definition and not an optional optimization, a number of coding idioms rely on it as a succinct conditional construct. Examples include:

Perl idioms:

POSIX shell idioms: This idiom presumes that  cannot fail.

Untested second condition leads to unperformed side effect
Despite these benefits, minimal evaluation may cause problems for programmers who do not realize (or forget) it is happening. For example, in the code if  is supposed to perform some required operation regardless of whether   is executed, such as allocating system resources, and   evaluates as false, then   will not execute, which could cause problems. Some programming languages, such as Java, have two operators, one that employs minimal evaluation and one that does not, to avoid this problem.

Problems with unperformed side effect statements can be easily solved with proper programming style, i.e., not using side effects in boolean statements, as using values with side effects in evaluations tends to generally make the code opaque and error-prone.

Reduced efficiency due to constraining optimizations
Short-circuiting can lead to errors in branch prediction on modern central processing units (CPUs), and dramatically reduce performance. A notable example is highly optimized ray with axis aligned box intersection code in ray tracing. Some compilers can detect such cases and emit faster code, but programming language semantics may constrain such optimizations.

An example of a compiler unable to optimize for such a case is Java's Hotspot virtual machine (VM) as of 2012.