Conceptcore
Short-circuit evaluation
Also called short-circuit evaluation, short circuit, minimal evaluation, McCarthy evaluation, conditional and, conditional or, lazy boolean operators, cand, cor, and then, or else, AndAlso, OrElse, null coalescing, optional chaining, guard expression.
Short-circuit evaluation computes the right operand of a Boolean and or or only when the left operand does not decide the result, so a test can guard the code that follows it.
- Applies to
- core-languages
Idea
In a and b, if a is false the result is false whatever b is, and in a or b, if a is true the result is true. Short-circuit evaluation uses this: the language evaluates the left operand first and evaluates the right operand only when it still matters. This is a rule about which code runs, not only about the result, so a program can write x != 0 and 12 / x > 2 and the division never runs with a zero.
calls = []
def check(name, value):
"""Record each call, so the output shows which operands ran."""
calls.append(name)
return value
def show(label, result):
print(f"{label:<28} -> {result!r:<6} evaluated: {', '.join(calls) or 'none'}")
calls.clear()
show("check(a, False) and check(b)", check("a", False) and check("b", True))
show("check(a, True) and check(b)", check("a", True) and check("b", True))
show("check(a, True) or check(b)", check("a", True) or check("b", False))
show("check(a, False) or check(b)", check("a", False) or check("b", False))
show("check(a, False) & check(b)", check("a", False) & check("b", True))
# The guard pattern: the right side runs only when it is safe.
for x in (0, 4):
print(f"x={x}:", x != 0 and 12 / x > 2)
# Python returns the operand that decided the result, not always a bool.
print(repr("" or "default"), repr("name" or "default"), repr(0 and 1 / 0), repr([] and None))
check(a, False) and check(b) -> False evaluated: a
check(a, True) and check(b) -> True evaluated: a, b
check(a, True) or check(b) -> True evaluated: a
check(a, False) or check(b) -> False evaluated: a, b
check(a, False) & check(b) -> False evaluated: a, b
x=0: False
x=4: True
'default' 'name' 0 []
check records each operand that runs. With and, a false left operand stops the evaluation, and with or, a true one does. The operator & is not short-circuit, so it runs both operands. The last line shows that Python returns the operand that decided the result, which is not always a bool.
How it works
The rule. The left operand is evaluated first. For and, the right operand is evaluated only if the left one is true; for or, only if it is false. Python states it as "The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned"1. JavaScript's && and || also return an operand value, and MDN calls && "a short-circuit operator"2. JavaScript's ?? returns "its right-hand side operand when its left-hand side operand is null or undefined", and it also skips the right operand when it does not need it3.
Typed languages. Java's && "evaluates its right-hand operand only if the value of its left-hand operand is true", and || does so only if the left operand is false. Java's & and | on boolean values evaluate both operands4. C# calls && the "short-circuiting" logical AND operator, and its & and | on bool also evaluate both5. The Go specification defines p && q as "if p then q else false" and p || q as "if p then true else q"6. Rust calls && and || lazy boolean operators: "the right-hand operand is only evaluated when the left-hand operand does not already determine the result of the expression"7.
C and C++. In C, there is a sequence point after the left operand of && and ||, and if the left operand of && is zero, "rhs is not evaluated at all"8. The side effects of the left operand are complete before the right operand starts, so p != NULL && p->qty > 0 is safe. C++ has the same rule for the built-in operators, but "overloaded operators behave like regular function calls and always evaluate both operands"9.
A guard. The common use is a test that protects the next one: a null check before a field access, a bounds check before an index, a zero check before a division, or a map lookup before the use of the value. The order of the operands matters, and a guard must come first.
Other forms. The conditional expression c ? a : b evaluates only one of a and b. Null-safe operators such as ?., ?? and ??= in C# and JavaScript and ?: in Kotlin stop at a null value. Library functions such as Python's any and all and Rust's Iterator::any stop at the first value that decides the result.
Where the order is not fixed. SQL does not promise short-circuit evaluation. The PostgreSQL documentation says that the inputs of an operator "are not necessarily evaluated left-to-right or in any other fixed order", so WHERE x > 0 AND y/x > 1.5 can still divide by zero. It recommends a CASE construct "when it is essential to force evaluation order"10.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the operators &&, ||, ??, ?. and the logical assignment operators of JavaScript, with the same short-circuit rules, but no example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin's && and || evaluate the right operand only when needed, and the safe call ?. and the Elvis operator ?: stop at null, but no example file exists because kotlinc is not installed. |
| SQL | Idiom | SQL does not fix the order in which AND and OR evaluate their operands, so a guard in a WHERE clause may not protect the next test. A CASE expression gives a fixed order in most databases. |
| Bash | Native | In a list such as cmd1 && cmd2, Bash runs cmd2 only if cmd1 succeeds, and || runs it only if cmd1 fails; && and || inside [[ ]] also short-circuit. No example file exists. |
| PowerShell | Native | PowerShell's -and and -or evaluate only the operands that they need, and && and || chain pipelines on success and failure, but no example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no expressions. |
| CSS | Does not apply | CSS conditions such as @supports and @media combine tests with and and or, but the tests have no side effects, so the order of evaluation does not matter. |
| Regular expressions | Does not apply | A regular expression has no Boolean operators on values. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | and, or; any, all; conditional expression |
| JavaScript | native | &&, ||, ??, ?.; &&=, ||=, ??= |
| TypeScript | native | as JavaScript |
| Java | native | &&, ||, ?:; & and | evaluate both |
| Kotlin | native | &&, ||, ?., ?: |
| C# | native | &&, ||, ??, ?., ??=; & and | evaluate both |
| Go | native | &&, || |
| Rust | native | &&, ||; bool::then, Option::unwrap_or_else |
| C | native | &&, ||, ?:, with a sequence point after the left operand |
| C++ | native | as C; an overloaded && or || evaluates both operands |
| Bash | native | && and || lists of commands; && and || in [[ ]] |
| PowerShell | native | -and, -or; && and || between pipelines |
| SQL | idiom | CASE WHEN; AND and OR have no fixed order |
| Regex | n/a | no Boolean operators |
| HTML | n/a | no expressions |
| CSS | n/a | no expressions with side effects |
The general-purpose languages in the table all have short-circuit and and or, so the verdict is native. They differ in what the operators return and which other operators stop early. Python and JavaScript return an operand, so or and || give a default value. Java, C#, Go, Rust, C and C++ return a Boolean. C# and JavaScript add null-safe operators, and C++ loses the rule when a program overloads &&. SQL is the exception: its AND and OR have no fixed order of evaluation, and CASE is the way to force one.
The example files show the rule and the common guards. Python shows that any and all stop early with a generator but not with a list. JavaScript shows ??, ?. and ??=. Java and C# compare && with &. Go shows a nil guard and a map lookup with ok. Rust shows that unwrap_or computes its argument first and unwrap_or_else does not. C shows a null guard, and C++ shows that an overloaded && evaluates both operands while a fold over && does not.
seen = []
def is_even(n):
seen.append(n)
return n % 2 == 0
nums = [1, 3, 4, 5, 7]
# any() and all() stop at the first value that decides the result.
print(any(is_even(n) for n in nums), seen)
seen.clear()
print(all(is_even(n) for n in nums), seen)
seen.clear()
# A list comprehension builds every value first, so nothing is skipped.
print(any([is_even(n) for n in nums]), seen)
# `or` treats 0 and "" as false, so it replaces values that are valid.
for retries in (None, 0, 3):
print(retries, "->", retries or 5, retries if retries is not None else 5)
# A chained comparison is short-circuit too: 1 < 0 is false, so 1 / 0 is not evaluated.
print(1 < 0 < 1 / 0)
True [1, 3, 4]
False [1]
True [1, 3, 4, 5, 7]
None -> 5 5
0 -> 5 0
3 -> 3 3
False
- Verdict: native.
andandorstop at the operand that decides the result and return that operand.anyandallstop early when they read a generator, but a list comprehension computes every value first, sois_evenruns five times.ortreats0as false, so it replaces a valid zero; a test withis not Nonekeeps it. A chained comparison such as1 < 0 < 1 / 0also stops at the first false part.
#include <iostream>
#include <string>
#include <vector>
int calls = 0;
bool check(bool v) {
++calls;
return v;
}
// A type with its own && operator.
struct Flag {
bool v;
};
Flag make(bool v) {
++calls;
return Flag{v};
}
bool operator&&(Flag a, Flag b) { return a.v && b.v; }
// A fold over && keeps short-circuit evaluation.
template <typename... Fs>
bool all_of(Fs... fs) {
return (... && fs());
}
int main() {
bool r = check(false) && check(true);
std::cout << std::boolalpha << r << " calls=" << calls << '\n';
// An overloaded && is a function call, so both operands are evaluated.
calls = 0;
bool r2 = make(false) && make(true);
std::cout << r2 << " calls=" << calls << '\n';
calls = 0;
bool r3 = all_of([] { return check(true); }, [] { return check(false); }, [] { return check(true); });
std::cout << r3 << " calls=" << calls << '\n';
// The guard pattern with a bounds test.
std::vector<std::string> words{"alpha", "beta"};
for (std::size_t i : {1u, 2u})
std::cout << i << ": " << (i < words.size() && words[i].size() > 3) << '\n';
}
false calls=1
false calls=2
false calls=2
1: true
2: false
- Verdict: native. The built-in
&&and||short-circuit as in C. An overloadedoperator&&is an ordinary function call, so both of its operands are evaluated, andmakeruns twice. A fold expression over&&uses the built-in operator, so it stops at the second lambda. The bounds testi < words.size()guards the index.
import java.util.Map;
public class Main {
static int calls = 0;
static boolean check(boolean v) {
calls++;
return v;
}
public static void main(String[] args) {
// && and || skip the right operand when the left one decides the result.
boolean r1 = check(false) && check(true);
System.out.println(r1 + " calls=" + calls);
calls = 0;
// & and | on booleans evaluate both operands.
boolean r2 = check(false) & check(true);
System.out.println(r2 + " calls=" + calls);
// The guard pattern: the right side runs only when it is safe.
String s = null;
System.out.println(s != null && s.length() > 3);
Map<String, Integer> stock = Map.of("pen", 4);
String key = "ink";
System.out.println(stock.containsKey(key) && stock.get(key) > 0);
// The conditional operator also evaluates only one branch.
int d = 0;
System.out.println(d == 0 ? "no division" : String.valueOf(10 / d));
}
}
false calls=1
false calls=2
false
false
no division
- Verdict: native.
&&and||skip the right operand when the left one decides the result, and&and|onbooleanevaluate both, so the second call runs. A null test befores.length()and acontainsKeytest beforegetare the usual guards. The conditional operator evaluates only the branch that it selects, so the division by zero does not run.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
static int calls = 0;
static bool check(bool v) {
calls++;
return v;
}
struct item {
const char *name;
int qty;
};
static const struct item *find(const struct item *xs, int n, const char *name) {
for (int i = 0; i < n; i++)
if (strcmp(xs[i].name, name) == 0)
return &xs[i];
return NULL;
}
int main(void) {
/* && and || have a sequence point after the left operand, and skip the right one when they can. */
bool r = check(false) && check(true);
printf("%d calls=%d\n", r, calls);
calls = 0;
r = (int)check(false) & (int)check(true); /* & evaluates both, in an unspecified order */
printf("%d calls=%d\n", r, calls);
/* The guard pattern: the pointer is tested before it is used. */
struct item stock[] = {{"pen", 4}, {"ink", 0}};
const char *names[] = {"pen", "ink", "cap"};
for (int i = 0; i < 3; i++) {
const struct item *p = find(stock, 2, names[i]);
printf("%s: %s\n", names[i], p != NULL && p->qty > 0 ? "in stock" : "none");
}
/* A bounds test before an index works the same way. */
int xs[3] = {5, 6, 7}, k = 3;
printf("%d\n", k < 3 && xs[k] > 0);
return 0;
}
0 calls=1
0 calls=2
pen: in stock
ink: none
cap: none
0
- Verdict: native.
&&and||have a sequence point after the left operand and skip the right one when they can.&evaluates both operands in an unspecified order, and clang warns about&onboolvalues, so the example casts toint. The testp != NULL && p->qty > 0readsqtyonly for an item that exists, andk < 3 && xs[k] > 0reads the array only inside its bounds.
int calls = 0;
bool Check(bool v)
{
calls++;
return v;
}
// && and || skip the right operand; & and | on bool evaluate both.
bool r1 = Check(false) && Check(true);
Console.WriteLine($"{r1} calls={calls}");
calls = 0;
bool r2 = Check(false) & Check(true);
Console.WriteLine($"{r2} calls={calls}");
// ?. stops at null, and ?? gives a value for null.
string? name = null;
Console.WriteLine(name?.Length ?? -1);
Console.WriteLine(name?.Trim().ToUpper() ?? "anonymous");
// ??= assigns only when the variable is null, so the right side runs once.
List<int>? cache = null;
cache ??= Load();
cache ??= Load();
Console.WriteLine($"{cache.Count} items, loads={loads}");
// A throw expression on the right side of ?? runs only for null.
string Require(string? s) => s ?? throw new ArgumentNullException(nameof(s));
Console.WriteLine(Require("ok"));
partial class Program
{
static int loads = 0;
static List<int> Load()
{
loads++;
return [1, 2, 3];
}
}
False calls=1
False calls=2
-1
anonymous
3 items, loads=1
ok
- Verdict: native.
&&and||short-circuit, and&and|onboolevaluate both operands.?.stops at null, and??supplies a value for null.??=callsLoadonly when the variable is null, so it runs once. Athrowexpression on the right of??runs only for a null argument.
const log = [];
const f = (name, v) => (log.push(name), v);
// && and || return an operand, and the right one runs only when needed.
console.log(f("a", 0) && f("b", 1), f("a", "x") || f("b", "y"), log.join(","));
// ?? replaces only null and undefined; || also replaces 0 and "".
const cfg = { retries: 0, name: "" };
console.log(cfg.retries || 5, cfg.retries ?? 5, JSON.stringify(cfg.name || "anon"), JSON.stringify(cfg.name ?? "anon"));
// ?. stops the whole chain when the left side is null or undefined.
const user = null;
log.length = 0;
console.log(user?.profile.getName(f("arg", 1)), log.length);
// Logical assignment assigns only when the operator would evaluate the right side.
const opts = { size: 10 };
opts.size ??= f("default size", 99);
opts.color ??= "red";
console.log(opts, log);
0 x a,a
5 0 "anon" ""
undefined 0
{ size: 10, color: 'red' } []
- Verdict: native.
&&and||return an operand and run the right one only when needed.||replaces0and"", and??replaces onlynullandundefined.?.stops the whole chain at a null value, so the argument ofgetNameis not computed.??=assigns, and computes its right side, only when the property is null or undefined.
package main
import "fmt"
type node struct {
val int
next *node
}
var calls int
func check(v bool) bool {
calls++
return v
}
func main() {
// && and || evaluate the right operand only when they need it.
r := check(false) && check(true)
fmt.Println(r, "calls =", calls)
calls = 0
r = check(true) || check(true)
fmt.Println(r, "calls =", calls)
// The guard pattern: a nil pointer is never dereferenced.
list := &node{1, &node{2, nil}}
for p := list; p != nil; p = p.next {
fmt.Println(p.val, p.next != nil && p.next.val > p.val)
}
// A map lookup with ok, then a test of the value.
stock := map[string]int{"pen": 4}
if n, ok := stock["ink"]; ok && n > 0 {
fmt.Println("ink in stock")
} else {
fmt.Println("no ink")
}
}
false calls = 1
true calls = 1
1 true
2 false
no ink
- Verdict: native. Go's
&&and||evaluate the right operand only when needed, and Go has no other short-circuit operators. The testp.next != nil && p.next.val > p.valnever reads through a nil pointer. In anifwith a short statement,ok && n > 0tests the value only when the key exists.
fn check(name: &str, v: bool, log: &mut Vec<String>) -> bool {
log.push(name.to_string());
v
}
fn expensive() -> i32 {
println!(" expensive() ran");
42
}
fn main() {
let mut log = Vec::new();
// && and || skip the right operand; & on bool evaluates both.
let a = check("a", false, &mut log) && check("b", true, &mut log);
println!("{a} {log:?}");
log.clear();
let b = check("a", false, &mut log) & check("b", true, &mut log);
println!("{b} {log:?}");
// unwrap_or takes a value, so its argument is computed first; unwrap_or_else takes a closure.
let x = Some(1);
println!("unwrap_or:");
println!(" {}", x.unwrap_or(expensive()));
println!("unwrap_or_else:");
println!(" {}", x.unwrap_or_else(expensive));
// bool::then runs the closure only for true.
let d = 0;
println!("{:?} {:?}", (d != 0).then(|| 10 / d), (2 != 0).then(|| 10 / 2));
}
false ["a"]
false ["a", "b"]
unwrap_or:
expensive() ran
1
unwrap_or_else:
1
None Some(5)
- Verdict: native.
&&and||skip the right operand, and&onboolevaluates both.unwrap_ortakes a value, so its argument is computed even when the option has a value;unwrap_or_elsetakes a function and calls it only when needed.bool::thenruns a closure only fortrue, so the division by zero does not run.
Variations and related ideas
- Eager operators. Java and C# have
&and|forbool, Ada hasandandorbesideand thenandor else, and Visual Basic hasAndandOrbesideAndAlsoandOrElse. The eager forms run both operands, which some code needs for their side effects. - Null coalescing and optional chaining.
??,?.and??=in C# and JavaScript,?:and?.in Kotlin, and??and?.in Swift test for null and skip the rest. See null references. - Lazy arguments in libraries.
Option::unwrap_or_elsein Rust,Optional.orElseGetin Java and the factory of Python'scollections.defaultdictcompute a default only when it is needed. Their eager forms,unwrap_or,orElseanddict.getwith a default, compute it first. - User-defined short-circuit operators. Lisp
andandorare special forms or macros, Swift has@autoclosureparameters, Scala has by-name parameters, and C# runs a user-defined&&through the operators&,trueandfalse. In Haskell, all evaluation is lazy, so&&is an ordinary function. - Order of evaluation. Short-circuit operators fix an order in languages that otherwise leave it open, such as C. See order of evaluation.
Pitfalls
- Side effects in the right operand. In
if (ok && count++ > 0),countchanges only whenokis true. Do not put an action that must always run in the right operand. See side effect. - Defaults that replace valid values.
x or 5in Python andx || 5in JavaScript replace0,""andFalseas well as a missing value. Use??in JavaScript and C#, orx if x is not None else 5in Python. - Arguments that look lazy.
opt.unwrap_or(expensive()),optional.orElse(load())andd.get(k, compute())run the default every time. Use the closure form when the default is expensive or has side effects. &for&&. A single&evaluates both operands, so a guard such asp != null & p.x > 0does not protect the access. In C,&also has an unspecified order and a different precedence.- Overloaded operators in C++. A class that overloads
&&or||loses short-circuit evaluation. Overload conversion toboolinstead. - Bash
a && b || c. This is not if-then-else:cruns whenafails and also whenbfails. Useif a; then b; else c; fi. - SQL guards.
WHERE x > 0 AND y / x > 1can still fail, because the database chooses the order. UseCASE.
Cost
Short-circuit operators compile to conditional branches, so a && b can cost a branch per operand. When both operands are cheap and have no side effects, a compiler can evaluate both and combine them with no branch, and a program can write & to ask for this. Put the operand that is cheap and that most often decides the result first: a fast test that usually fails saves the work of the slow test. For any and all over a sequence, short-circuit evaluation can stop after the first element instead of reading all n.
History
John McCarthy's 1960 paper on LISP defined the propositional connectives with conditional expressions, so that "p ∧ q is computed by first computing p, and if p is false q is not computed"11. In BCPL and B, & and | were bitwise in ordinary expressions but short-circuit inside the condition of an if. Dennis Ritchie wrote that "At the suggestion of Alan Snyder, I introduced the && and || operators to make the mechanism more explicit" in C, and that their late introduction explains why & has a lower precedence than ==12.
Not everyone liked the rule. Edsger W. Dijkstra called the conditional connectives "cand" and "cor" and wrote that they "complicate the formal reasoning about programs"13. Most languages kept them, and the term McCarthy evaluation names the idea after him13. Later languages added null-safe operators that use the same rule.
References
- Expressions, The Python Language Reference, 6.11 Boolean operations
- Logical AND (&&), MDN Web Docs, Short-circuit evaluation
- Nullish coalescing operator (??), MDN Web Docs, Description
- The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.23 Conditional-And Operator &&; 15.24 Conditional-Or Operator ||
- Boolean logical operators, C# language reference, Conditional logical AND operator &&
- The Go Programming Language Specification, Logical operators
- Operator expressions, The Rust Reference, Lazy boolean operators
- Logical operators, C reference, cppreference.com, Logical AND
- Logical operators, C++ reference, cppreference.com, Description
- Value Expressions, PostgreSQL documentation, 4.2.14 Expression Evaluation Rules
- Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, John McCarthy, 1960, Section 2, Conditional expressions
- The Development of the C Language, Dennis M. Ritchie, Embryonic C
- Short-circuit evaluation, Wikipedia, Introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag D7SGB5 Edit this page History Report an error Markdown