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
- 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. - 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); - 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. - Measure. Write a loop evaluating
i > 100 && i < 200ten thousand times withialways 5. Record SPIM's instruction count. How many of those instructions were spent evaluating an operand whose value could not matter? - 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.