Short-circuit evaluation

{{Short description|Programming language construct}}

{{Distinguish|Short-circuit test}}

{{More citations needed|date=August 2013}}

{{Evaluation strategy}}

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 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 (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:

{{Quote

|text = 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.

|author = Edsger W. DijkstraEdsger W. Dijkstra "On a somewhat disappointing correspondence", EWD1009-0, 25 May 1987 [http://www.cs.utexas.edu/users/EWD/ewd10xx/EWD1009.PDF full text]}}

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 {{code|AND}} takes precedence over {{code|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.{{cite web |title=Shell Command Language |url=https://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html |website=pubs.opengroup.org}}{{rp|at=§2.9.3}}

The following simple left-to-right evaluator enforces a precedence of {{code|AND}} over {{code|OR}} by a {{code|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.{{cite arXiv |last1=Bergstra |first1=Jan A. |last2=Ponse |first2=A. |last3=Staudt |first3=D.J.C. |date=2010 |title=Short-circuit logic |eprint=1010.3674|class=cs.LO}}

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. In some languages, the bitwise operators can be used as eager boolean operators. For other languages, bitwise operators are not included in the list, because they do not take boolean values or have a result type different from the respective short-circuit operators.

Note that there are more short-circuit operators, for example the ternary conditional operator, which is cond ? e1 : e2 (C, C++, Java, PHP), if cond then e1 else e2 (ALGOL, Haskell, Kotlin, Rust), e1 if cond else e2 (Python). Please take a look at ternary conditional operator#Usage.

class="wikitable"

|+ Boolean operators in common languages

! Language !! Eager operators !! Short-circuit operators !! Result type

Ada

| and, or

| and then, or else

| Boolean

ALGOL 68

| and, &, ∧ ; or, ∨

| {{depends|andf , orf (both user defined)}}

| Boolean

APL

| ,

| :AndIf, :OrIf

| Boolean

awk

| none

| &&,

| Boolean

C, Objective-C

| &, |{{efn |name=bitwise_c |1=The bitwise operators behave like boolean operators when both arguments are of type bool or take only the values 0 or 1.[http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf ISO/IEC 9899 standard, sections 6.2.5, 6.3.1.2, 6.5 and 7.16.]}}

| &&,

[http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf ISO/IEC 9899 standard, section 6.5.13]

| int

C++{{efn |name=cpp |1=When overloaded, the operators && and are eager and can return any type.}}

| none

| &&,

[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf ISO/IEC IS 14882 draft.]

| Boolean

C#

| &, |

| &&,

| Boolean

D{{efn |name=d |1=This only applies to runtime-evaluated expressions, static if and static assert. Expressions in static initializers or manifest constants use eager evaluation.}}

| &, |

| &&,

| Boolean

Eiffel

| and, or

| and then, or else

| Boolean

Erlang

| and, or

| andalso, orelse

| Boolean

Fortran{{efn |name=fortran |1=Fortran operators are neither short-circuit nor eager: the language specification allows the compiler to select the method for optimization.}}

| .and., .or.

| .and., .or.

| Boolean

Go, Haskell, OCaml{{efn |name=bitwise_without_bool |1=In lua and OCaml, bitwise operators &, | (OCaml land, lor) are restricted to integers and cannot be used with Booleans.}}

| none

| &&,

| Boolean

Java, R, Swift

| &, |

| &&,

| Boolean

JavaScript

| none

| &&,

| Last value

Julia

| none

| &&,

| Last value

Kotlin

| and, or

| &&,

| Boolean

Lisp, Lua{{efn |name=bitwise_without_bool}}, Scheme

| none

| and, or

| Last value

MATLAB{{efn |name=matlab |1=The operator & behaves like a short-circuit operator when used in a statement following if or while.{{cite web |author= |title=and, & |url=https://www.mathworks.com/help/matlab/ref/double.and.html |website=MathWorks Help Center |access-date=2025-02-02}}}}

| &, |

| &, |, &&,

| Boolean

MUMPS (M)

| &, !

| none

| Numeric

Modula-2

| none

| AND, OR

| Boolean

Pascal

| and, or{{efn |name=pascal-1 |1=ISO/IEC 10206:1990 Extended Pascal allows, but does not require, short-circuiting.}}{{efn |name=delphi |1=Delphi and Free Pascal default to short circuit evaluation. This may be changed by compiler options but does not seem to be used widely.}}

| and_then, or_else{{efn |name=delphi}}

| Boolean

Perl

| &, |

| &&, and,

, or

| Last value

PHP

| none

| &&, and,

, or

| Boolean

POSIX shell, Bash

| none

| &&,

| Numeric (exit code)

PowerShell Scripting Language

| none

| -and, -or

| Boolean

Python

| &, |

| and, or

| Last value

Ruby

| &, |

| &&, and,

, or{{Cite web |title=operators - Documentation for Ruby 3.3 |url=https://docs.ruby-lang.org/en/3.3/syntax/operators_rdoc.html#label-Logical+Operators |access-date=2024-04-02 |website=docs.ruby-lang.org}}

| Last value

Rust

| &, |

| &&,

{{Cite web|url=https://doc.rust-lang.org/std/ops/index.html|title=std::ops - Rust|website=doc.rust-lang.org|access-date=2019-02-12}}

| Boolean

Smalltalk

| &, |

| and:, or:{{efn |name=smalltalk |1=Smalltalk uses short-circuit semantics as long as the argument to and: is a block (e.g., {{code|false and: [Transcript show: 'Wont see me']|smalltalk}}).}}

| Boolean

Standard ML

| {{Unknown}}

| andalso, orelse

| Boolean

Visual Basic .NET

| And, Or

| AndAlso, OrElse

| Boolean

Visual Basic, Visual Basic for Applications (VBA)

| And, Or

| none

| Numeric

{{notelist}}

Common use

=Avoiding undesired side effects of the second argument=

Usual example, using a C-based language:

int denom = 0;

if (denom != 0 && num / denom)

{

... // ensures that calculating num/denom never results in divide-by-zero error

}

Consider the following example:

int a = 0;

if (a != 0 && myfunc(b))

{

do_something();

}

In this example, short-circuit evaluation guarantees that myfunc(b) 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 is_first_char_valid_alpha_unsafe(const char *p)

{

return isalpha(p[0]); // SEGFAULT highly possible with p == NULL

}

bool is_first_char_valid_alpha(const char *p)

{

return p != NULL && isalpha(p[0]); // 1) no unneeded isalpha() execution with p == NULL, 2) no SEGFAULT risk

}

=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:{{cite web |url=https://unix.stackexchange.com/questions/190543/what-does-mean-in-bash |title=What does {{!}}{{!}} mean in bash? |publisher=stackexchange.com |access-date=2019-01-09}}

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 (or forget) it is happening. For example, in the code

if (expressionA && myfunc(b)) {

do_something();

}

if myfunc(b) is supposed to perform some required operation regardless of whether do_something() is executed, such as allocating system resources, and expressionA evaluates as false, then myfunc(b) 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.{{cite web |url=http://www.itu.dk/people/sestoft/papers/SondergaardSestoft1990.pdf |title=Referential Transparency, Definiteness and Unfoldability |publisher=Itu.dk |access-date=2013-08-24}}

=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.{{clarify|date=November 2010}} Some compilers can detect such cases and emit faster code, but programming language semantics may constrain such optimizations.{{citation needed|date=October 2016}}

An example of a compiler unable to optimize for such a case is Java's Hotspot virtual machine (VM) as of 2012.{{cite web |last=Wasserman |first=Louis |date=11 July 2012 |title=Java: What are the cases in which it is better to use unconditional AND (& instead of &&) |url=https://stackoverflow.com/a/11412121 |website=Stack Overflow}}

See also

References