Do Loop with Variable
Quirin Schroll
qs.il.paperinik at gmail.com
Mon Jul 28 12:26:40 UTC 2025
On Thursday, 17 July 2025 at 13:43:33 UTC, Dukc 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);
>> }
>> ```
>
> I would probably prefer if symbols declared inside the do
> statement would be accessible in the condition. Would be a
> breaking change though, requiring a warning from the compiler
> if a symbol declared both inside and outside the do block would
> be used in `while` and probably doing it over an edition switch.
Realistically, if you reference a symbol that’s defined within
the loop in the condition that coincidentally resolves because
it’s *also* defined in the outer scope, that should be an error.
You can always refer to such a symbol in an unambiguous way.
Here’s what I mean:
```d
struct S
{
int x;
void f()
{
do { int x; …; }
while (x > 0); // likely a bug
}
}
```
The `x` in `x > 0` refers to `this.x`, not the local variable
defined in the loop. My sense is: No-one actually writes such
code intentionally. If it really makes sense to name a
`do`-loop-body variable the same as an outer-scope variable used
in its condition, it’s not too much to ask to make this clear:
Use `this.x` or `.x` (global) or whatever. (I filed this as an
issue.)
More information about the dip.ideas
mailing list