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
.
The short-circuit expression x and y
is equivalent to the conditional expression (True if y else False) if x else False
; the expression x or y
is equivalent to True if x else True if y else False
.
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.
- 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.