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.
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.2: §2.9.3
The following simple left-to-right evaluator enforces a precedence of AND over OR by a continue:
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.3
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.
Usual example, using a C-based language:
Consider the following example:
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.
Both are illustrated in the following C snippet where minimal evaluation prevents both null pointer dereference and excess memory fetches:
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:19
This idiom presumes that echo cannot fail.
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 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.20
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.21
Edsger W. Dijkstra "On a somewhat disappointing correspondence", EWD1009-0, 25 May 1987 full text /wiki/Edsger_W._Dijkstra ↩
"Shell Command Language". pubs.opengroup.org. https://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html ↩
Bergstra, Jan A.; Ponse, A.; Staudt, D.J.C. (2010). "Short-circuit logic". arXiv:1010.3674 [cs.LO]. /wiki/ArXiv_(identifier) ↩
The bitwise operators behave like boolean operators when both arguments are of type bool or take only the values 0 or 1.[4] ↩
ISO/IEC 9899 standard, section 6.5.13 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf ↩
When overloaded, the operators && and || are eager and can return any type. /wiki/Operator_overloading ↩
ISO/IEC IS 14882 draft. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf ↩
This only applies to runtime-evaluated expressions, static if and static assert. Expressions in static initializers or manifest constants use eager evaluation. ↩
Fortran operators are neither short-circuit nor eager: the language specification allows the compiler to select the method for optimization. /wiki/Compiler ↩
In lua and OCaml, bitwise operators &, | (OCaml land, lor) are restricted to integers and cannot be used with Booleans. ↩
The operator & behaves like a short-circuit operator when used in a statement following if or while.[7] ↩
ISO/IEC 10206:1990 Extended Pascal allows, but does not require, short-circuiting. /wiki/Pascal_(programming_language)#ISO/IEC_10206:1990_Extended_Pascal ↩
Delphi and Free Pascal default to short circuit evaluation. This may be changed by compiler options but does not seem to be used widely. /wiki/Delphi_(software) ↩
"operators - Documentation for Ruby 3.3". docs.ruby-lang.org. Retrieved 2024-04-02. https://docs.ruby-lang.org/en/3.3/syntax/operators_rdoc.html#label-Logical+Operators ↩
"std::ops - Rust". doc.rust-lang.org. Retrieved 2019-02-12. https://doc.rust-lang.org/std/ops/index.html ↩
Smalltalk uses short-circuit semantics as long as the argument to and: is a block (e.g., false and: [Transcript show: 'Wont see me']). ↩
"What does || mean in bash?". stackexchange.com. Retrieved 2019-01-09. https://unix.stackexchange.com/questions/190543/what-does-mean-in-bash ↩
"Referential Transparency, Definiteness and Unfoldability" (PDF). Itu.dk. Retrieved 2013-08-24. http://www.itu.dk/people/sestoft/papers/SondergaardSestoft1990.pdf ↩
Wasserman, Louis (11 July 2012). "Java: What are the cases in which it is better to use unconditional AND (& instead of &&)". Stack Overflow. https://stackoverflow.com/a/11412121 ↩