[Language construct idea] The for loop with prepare step

Quirin Schroll qs.il.paperinik at gmail.com
Tue Feb 13 11:06:37 UTC 2024


On Monday, 12 February 2024 at 16:14:40 UTC, Paul Backus wrote:
> On Monday, 12 February 2024 at 15:58:50 UTC, Quirin Schroll 
> wrote:
>> Extend `for` to `for (init; prepare; condition; increment) 
>> body`.
>>
>> The step `prepare` is executed before each check.
>
> I've never heard of anything like this in any other programming 
> language, so I'm skeptical by default.
>
> Do you have any examples of code that this feature would 
> improve?

I thought it was obvious, but okay:

Instead of writing something like:
```d
import core.stdc.stdio;
for (int c; (c = fgetc(fp)) != EOF; ) { }
```
once could do:
```d
for (import core.stdc.stdio; int c = fgetc(fp); c != EOF; ) { }
```
Example source: https://en.cppreference.com/w/c/io/fgetc (There, 
`c` is only used in the loop, and the declaration of `c` directly 
precedes the `while` loop only because in C89, `for` loops cannot 
use declarations.)

It’s a standard example of a probably not that niche pattern. 
I’ve written this loop a lot of times learning and doing projects 
with C.


More information about the Digitalmars-d mailing list