Commissioned for this museum · after Tom Duff's device, Lucasfilm, 1983

The Loop That Starts in the Middle

C·1983·23 lines·687 bytes

Curator’s note

Read it once and it looks like a mistake. A switch opens, and the first case opens a do loop — and then the remaining cases appear *inside* that loop, interleaved with its body. The braces do not nest the way the indentation suggests, and most people's first reaction is that this cannot possibly be a legal program.

It is legal, and it is legal for a dull reason. C says a case label may sit in front of any statement anywhere inside the switch, including a statement that happens to be in the middle of a loop. The switch jumps to a label; the loop then runs as a loop, from wherever the jump landed. Two ordinary mechanisms, put together in a way nobody intended.

What it buys is the cost of the test at the bottom of a copying loop. Copy one short at a time and you pay for --n > 0 once per short. Unroll the body eight times and you pay it once per eight — but then you have to deal with the remainder, and the usual way is a second little loop before or after the big one. Duff's arrangement deals with the remainder by *entering* the unrolled body partway down, so the leftovers happen on the first pass and every pass after that is a full eight.

Tom Duff wrote it at Lucasfilm in 1983 and said of it: "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against."

Checked, for every count from one to two hundred: it copies exactly that many.