Do Loop with Variable

Quirin Schroll qs.il.paperinik at gmail.com
Thu Jul 17 13:28:36 UTC 2025


On Wednesday, 9 July 2025 at 17:13:27 UTC, Patrick Schluter wrote:
> On Tuesday, 8 July 2025 at 17:24:11 UTC, jmh530 wrote:
>> On Tuesday, 8 July 2025 at 16:40:24 UTC, Quirin Schroll wrote:
>>> I have the feeling this isn’t gonna fly, but I’ll say it 
>>> anyways because maybe someone finds a solution.
>>> ```d
>>> do (int x = 0)
>>> { }
>>> while (++x < 10);
>>> ```
>>> which would be equivalent to
>>> ```d
>>> {
>>>     int x = 0;
>>>     do
>>>     { }
>>>     while (++x < 10);
>>> }
>>> ```
>>> [snip]
>>
>> What is your motivation for this? Making sure `x` doesn't stay 
>> around or making sure it doesn't conflict with `x` elsewhere 
>> in the program?
>
> Exactly that. I really would like to have this also in C.
> I would even go as far as having a special scope rule only 
> applying to `do {} while()`. Where the scope extends to closing 
> parenthesis of the `while`.
>
> ```c
>     do {
>        int a = 0;
>        ...
>     } while(a++ < 10);
> ```
> I know that something like that would never fly.

In C, yeah, it’s not gonna be added. But D? It could be added. D 
doesn’t allow local variable shadowing, which means that `a` in 
`while (a++ < 10)` can’t be another local variable (because that 
would shadow the one defined in the loop body). It could 
theoretically be a member or global variable, though, but I doubt 
anyone would intentionally write such code (likely it’s a bug).

Essentially, it would mean that
```
do Statement while (Condition);
```
would be equivalent to:
```d
{
start:
     Statement
     if (Condition) goto start;
}
```
instead of:
```d
{
start:
     { Statement }
     if (Condition) goto start;
}
```

It wouldn’t be the only `{}` that don’t introduce scope. `static 
if`/`version`/`debug` don’t introduce scope and the first `for` 
doesn’t introduce scope either:
```d
for ({int i; double d = 10;} i < 10; ++i, d /= 2) { }
```


More information about the dip.ideas mailing list