Short-circuit evaluation


Short-circuit evaluation, minimal evaluation, or McCarthy evaluation 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 AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.
In programming languages with lazy evaluation, the usual Boolean operators short-circuit. In others, both short-circuit and standard Boolean operators are available. For some Boolean operations, like exclusive or, 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, where side effects are important, short-circuit operators introduce a sequence point: they completely evaluate the first argument, including any side effects, before 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:

Definition

In any programming language that implements short-circuit evaluation, the expression x and y is equivalent to the conditional expression if x then y else x, and the expression x or y is equivalent to if x then x else y. In either case, x is only evaluated once.
The generalized definition above accommodates loosely typed languages that have more than the two truth-values True and False, 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 if x then y else false and if x then true else y respectively for the Boolean case.

Precedence

Although takes precedence over 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 over by a :
function short-circuit-eval
let result := True
for each in :
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.

Comparison with bitwise operators

& and | are bitwise operators that occur in many programming languages. The major difference is that bitwise operations operate on the individual bits of a binary numeral, whereas conditional operators operate on logical operations. Additionally, expressions either side of a bitwise operator are always evaluated. In some languages, including Java and C#, they can be used on Boolean operands to force both sides to be evaluated.

if
If expression 1 is true, expressions 2 and 3 are not checked.

if
This checks expressions 2 and 3, even if expression 1 is true.
Short-circuit operators can thus reduce run times by avoiding unnecessary calculations. They can also avoid null exceptions when expression 1 checks whether an object is valid.

Support in common programming and scripting languages

The following table is restricted to common programming languages and the basic Boolean operators for logical conjunction AND and logical disjunction OR. Bitwise operators are shown only for languages that allow them to be used as eager Boolean operators and have the same return type.
Note that there are more short-circuit operators, for example the ternary conditional operator, which is cond ? e1 : e2, if cond then e1 else e2, e1 if cond else e2. Please take a look at ternary conditional operator#Usage.
LanguageEager operatorsShort-circuit operatorsResult type
Adaand, orand then, or elseBoolean
ALGOL 68and, &, ∧ ; or, ∨Boolean
APL, :AndIf, :OrIfBoolean
awk&&, ||Boolean
C, Objective-C&, |&&, ||int
C++&&, ||Boolean
C#&, |&&, ||Boolean
D&, |&&, ||Boolean
Eiffeland, orand then, or elseBoolean
Erlangand, orandalso, orelseBoolean
Fortran.and., .or..and., .or.Boolean
Go, Haskell, OCaml&&, ||Boolean
Java, R, Swift&, |&&, ||Boolean
JavaScript&&, ||Last value
Julia&&, ||Last value
Kotlinand, or&&, ||Boolean
Lisp, Lua, Schemeand, orLast value
MATLAB&, |&, |, &&, ||Boolean
MUMPS &, !Numeric
Modula-2AND, ORBoolean
Pascaland, orand_then, or_elseBoolean
Perl&, |&&, and, ||, orLast value
PHP&&, and, ||, orBoolean
POSIX shell, Bash&&, ||Numeric
PowerShell Scripting Language-and, -orBoolean
Python&, |and, orLast value
Ruby&, |&&, and, ||, orLast value
Rust&, |&&, ||Boolean
Smalltalk&, |and:, or:Boolean
Standard MLandalso, orelseBoolean
Visual Basic.NETAnd, OrAndAlso, OrElseBoolean
Visual Basic, Visual Basic for Applications And, OrNumeric

Common use

Avoiding undesired side effects of the second argument

Usual example, using a C-based language:

int denom = 0;
if

Consider the following example:

int a = 0;
if

In this example, short-circuit evaluation guarantees that myfunc is never called. This is because a != 0 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:

bool isFirstCharValidAlphaUnsafe
bool isFirstCharValidAlpha

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:

some_condition or die; # Abort execution if some_condition is false
some_condition and die; # Abort execution if some_condition is true

POSIX shell idioms:

modprobe -q some_module && echo "some_module installed" || echo "some_module not installed"

This idiom presumes that echo cannot fail.

Possible problems

Untested second condition leads to unperformed side effect

Despite these benefits, minimal evaluation may cause problems for programmers who do not realize it is happening. For example, in the code

if

if myFunc is supposed to perform some required operation regardless of whether doSomething is executed, such as allocating system resources, and expressionA evaluates as false, then myFunc 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, 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 as of 2012.