[Language construct idea] The for loop with prepare step
Quirin Schroll
qs.il.paperinik at gmail.com
Mon Feb 12 15:58:50 UTC 2024
Extend `for` to `for (init; prepare; condition; increment) body`.
The step `prepare` is executed before each check. Ignoring scope,
the above is lowered to:
```d
init;
start:
prepare;
if (!condition) goto end;
body;
increment;
goto start;
end:
```
`continue` is also `goto start`.
Sometimes, you want to execute something before each condition
check, no matter if it’s when entering the loop or when looping
back.
D’s best options for that is:
* Repeat yourself in `init` and `increment`, possibly using a
local function if the step is more than 1 simple instruction.
* Use `{ prepare; return condition; }()`. While not a DRY
violation, this has the disadvantage that you cannot declare a
variable in `prepare` that’s present in the loop’s `increment` or
`body`.
More information about the Digitalmars-d
mailing list