ArticleslgStudy

engineering

Short-circuit evaluation

Short-circuit evaluation is a engineering topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Short-circuit evaluation rather than just read about it. In short: 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…

Key takeaways

  • Short-circuit evaluation belongs to engineering; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Short-circuit evaluation to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Short-circuit evaluation from memory before moving on to harder problems.

Reference excerpt

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

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.

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 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. The following simple left-to-right evaluator enforces a precedence of AND over OR by a 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.

Comparison with bitwise operators & and | are bitwise operators that occur in many programming languages. The major difference is that bitwise operations operate on the individual bits of a binary numeral, whereas conditional operators operate on logical operations. Additionally, expressions either side of a bitwise operator are always evaluated. In some languages, including Java and C#, they can be used on Boolean operands to force both sides to be evaluated.

If expression 1 is true, expressions 2 and 3 are not checked. This checks expressions 2 and 3, even if expression 1 is true. Short-circuit operators can thus reduce run times by avoiding unnecessary calculations. They can also avoid null exceptions when expression 1 checks whether an object is valid.

Support in common programming, hardware-description 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. Bitwise operators are shown only for languages that allow them to be used as eager Boolean operators and have the same return type. Many languages have other non-strict operators, notably conditional expressions with varying syntax, such as the ternary conditional. The Elvis operator is syntax for a short-circuit AND which returns the last value.

Common use

Avoiding undesired side effects of the second argument 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.

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:

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:

POSIX shell idioms:

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

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Short-circuit evaluation

Start with the simplest possible case. Write down what Short-circuit evaluation claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In engineering, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Short-circuit evaluation before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Short-circuit evaluation ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Short-circuit evaluation

In research
Short-circuit evaluation appears in engineering research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Short-circuit evaluation in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Short-circuit evaluation is common in secondary-school and first-year university syllabi. It links to neighbouring topics Compiler optimizations, Conditional constructs, Evaluation strategy, so understanding it makes those chapters shorter.
In everyday life
Look for Short-circuit evaluation outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Short-circuit evaluation” →

How to study Short-circuit evaluation in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Short-circuit evaluation means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Short-circuit evaluation out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Short-circuit evaluation in simple terms?

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 express…

Why does Short-circuit evaluation matter?

Because it connects several engineering ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Short-circuit evaluation?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Short-circuit evaluation.

Tags

  • Compiler optimizations
  • Conditional constructs
  • Evaluation strategy
  • Implementation of functional programming languages

Keep exploring