Topic 5 · Class activity 3 · Week 13 · Wednesday

Short-Circuit or Not — Decide It

Both of Dragon's translations, a truth table, the bitwise-and trap, and a measurement.

Format pairsTime 50 min

The point

Short-circuit evaluation is a language-design decision most people inherit without noticing. Make it consciously, and measure what it costs.

Do this

  1. Write both lowerings on paper for A && B — the numeric one and the flow-of-control one from Dragon §6.6. Count instructions in each listing, and count how many execute when A is false.
  2. Implement the eager version and confirm the truth table:
    print(1 && 1);  print(1 && 0);  print(0 && 1);  print(0 && 0);
    print(1 || 0);  print(0 || 0);  print(!0);  print(!5);
  3. Test the trap. print(2 && 1); must print 1. If it prints 0, fix it and explain the fix in one sentence naming the instruction you added.
  4. Measure. Write a loop evaluating i > 100 && i < 200 ten thousand times with i always 5. Record SPIM's instruction count. How many of those instructions were spent evaluating an operand whose value could not matter?
  5. Decide. Would you implement short-circuiting? Under what change to the language does it stop being optional? Two sentences.
The answer to the second half of step 5

The moment expressions can have side effects. Your language already allows function calls in expressions, so n != 0 && safeDivide(x, n) is a program whose correctness depends on the answer. At that point short-circuiting is not an optimization — it is part of what the operator means, which is why C specifies it in the standard rather than leaving it to implementations.

Deliverable

Both lowerings with instruction counts; your eight truth-table results; the one-sentence fix for step 3; your measurement; and your two-sentence decision. Feeds Lab Question 24.