Topic 4 · Class activity 2 · Week 9 · Friday

for vs while — a Design Decision

Lower directly or desugar? Write both, settle the degenerate cases, and let continue tell you which is riskier.

Format pairs, at a laptopTime 50 min

The point

for is a design decision, not a feature. Make it deliberately, and be able to defend it.

Do this

  1. Two implementations, on paper. (a) Lower for directly. (b) Desugar it in the parser into a while whose body is { B; U; }, preceded by I. Write the TAC each produces for the same loop.
  2. Compare the listings. Identical? If not, which is shorter, and does the difference survive optimization?
  3. Decide the degenerate cases before coding. For each, is it a parse error or a legal program, and what does it mean?
    for (; i < 5; i = i + 1) ...     no initializer
    for (i = 0; ; i = i + 1) ...     no condition
    for (i = 0; i < 5; ) ...         no update
    for (;;) ...                     nothing at all
  4. Implement your choice, then write a test exercising all four degenerate forms and confirm each behaves as you decided.
  5. The continue question. You are not implementing continue, but answer on paper: in a while, which label would it jump to? In a for? Why are those different, and what does that tell you about desugaring?
  6. Argue. Two sentences: which implementation would you ship, and what would change your mind?
On step 5

In a while, continue jumps to the top — the same label the back edge targets. In a for it must jump to the update, or the loop variable never advances and you have written an infinite loop. So a naive desugaring that discards the distinction between 'top of loop' and 'start of update' is correct until the day you add continue — which is a good argument for keeping two labels even if you desugar.

Deliverable

Both TAC listings; your decision table for the four degenerate forms; a working implementation; your written answer on continue; and your two-sentence argument. Feeds Lab Question 18.