[Issue 24395] New: Allow braced statements in loop conditions
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Wed Feb 14 16:19:51 UTC 2024
https://issues.dlang.org/show_bug.cgi?id=24395
Issue ID: 24395
Summary: Allow braced statements in loop conditions
Product: D
Version: D2
Hardware: All
OS: All
Status: NEW
Severity: enhancement
Priority: P1
Component: dmd
Assignee: nobody at puremagic.com
Reporter: qs.il.paperinik at gmail.com
For loops allow a braced sequence of statements in the first section:
```d
// Valid D code:
for ({int i = 1; int n = 10;} i < n; ++i) { }
```
Variables declared there are visible in the following two sections and the loop
body.
I propose to allow this for the condition as well:
Like the initial section, the condition could be a braced sequence of
statements, where the last statement would be special-cased in the sense that
it must evaluate to something that can be interpreted as a Boolean condition.
E.g.:
```d
// Proposed D code:
for (int i = 0; {int n = 10 - i; i < n;} ++i) { }
```
The main difference between this and an immediately invoked lambda is probably
scope: The braces as part of the `for` loop construct do not create a scope;
the variable `n` in the example would be visible in the condition, the
increment (what `++i` is) and the body of the for loop.
It would make sense to allow the same for the condition of the `while` loop.
That allows e.g. to rewrite the standard C `fgetc` pattern in a cleaner
fashion:
```d
while ({int c = std::fgetc(fp); c != EOF;}) { ... }
```
To be consistent, it should also work on a `do…while` loop, albeit not being
that useful as the scope of variables declared in its condition should not be
visible in the loop body.
--
More information about the Digitalmars-d-bugs
mailing list