Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after
John McCarthy) is the semantics of some
Boolean operators in some
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s 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
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an Expression (computer science), expression until its value is needed (non-strict evaluation) and which avoids repeated eva ...
(
Lisp
Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation.
Originally specified in the late 1950s, ...
,
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
,
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
), the usual
Boolean operators short-circuit. In others (
Ada,
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
,
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), was an ancient sacred precinct and the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient Classical antiquity, classical world. The A ...
), both short-circuit and standard Boolean operators are available. For some Boolean operations, like ''
exclusive or
Exclusive or, exclusive disjunction, exclusive alternation, logical non-equivalence, or logical inequality is a logical operator whose negation is the logical biconditional. With two inputs, XOR is true if and only if the inputs differ (on ...
'' (XOR), it is impossible to short-circuit, because both operands are always needed to determine a result.
Short-circuit operators are, in effect,
control structure
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
s 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
In medicine, a side effect is an effect of the use of a medicinal drug or other treatment, usually adverse but sometimes beneficial, that is unintended. Herbal and traditional medicines also have side effects.
A drug or procedure usually used ...
, before (optionally) processing the second argument.
ALGOL 68
ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language member of the ALGOL family that was conceived as a successor to the ALGOL 60 language, designed with the goal of a much wider scope of application and ...
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
In computer science, conditionals (that is, conditional statements, conditional expressions and conditional constructs) are programming language constructs that perform different computations or actions or return different values depending on t ...
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-value
In logic and mathematics, a truth value, sometimes called a logical value, is a value indicating the relation of a proposition to truth, which in classical logic has only two possible values ('' true'' or '' false''). Truth values are used in c ...
s
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 (''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
The following table is restricted to common programming languages and the basic boolean operators for
logical conjunction
In logic, mathematics and linguistics, ''and'' (\wedge) is the Truth function, truth-functional operator of conjunction or logical conjunction. The logical connective of this operator is typically represented as \wedge or \& or K (prefix) or ...
AND
and
logical disjunction
In logic, disjunction (also known as logical disjunction, logical or, logical addition, or inclusive disjunction) is a logical connective typically notated as \lor and read aloud as "or". For instance, the English language sentence "it is ...
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
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
,
PHP),
if cond then e1 else e2
(
ALGOL
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
,
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
,
Kotlin,
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
),
e1 if cond else e2
(
Python). Please take a look at
ternary conditional operator#Usage.
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)
Consider the following example:
int a = 0;
if (a != 0 && myfunc(b))
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.
# 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.
# 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)
bool is_first_char_valid_alpha(const char *p)
Idiomatic conditional construct
Since minimal evaluation is part of an operator's semantic definition and not an optional
optimization
Mathematical optimization (alternatively spelled ''optimisation'') or mathematical programming is the selection of a best element, with regard to some criteria, from some set of available alternatives. It is generally divided into two subfiel ...
, a number of coding idioms rely on it as a succinct conditional construct. Examples include:
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
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 (or forget) it is happening. For example, in the code
if (expressionA && myfunc(b))
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
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, 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
In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g., an if–then–else structure) will go before this is known definitively. The purpose of the branch predictor is to improve the flow ...
on modern
central processing unit
A central processing unit (CPU), also called a central processor, main processor, or just processor, is the primary Processor (computing), processor in a given computer. Its electronic circuitry executes Instruction (computing), instructions ...
s (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
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
's
Hotspot virtual machine (VM) as of 2012.
See also
*
Don't-care term
*
Null coalescing operator
The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, such as (in alphabetical order): C# since version 2.0, Dart since version 1.12.0, PHP since versi ...
*
Ternary conditional operator
References
{{John McCarthy
Articles with example C code
Articles with example Perl code
Compiler optimizations
Conditional constructs
Evaluation strategy
Implementation of functional programming languages