Can we fix this?

Max Samukha maxsamukha at gmail.com
Thu Sep 30 12:55:48 UTC 2021


On Thursday, 30 September 2021 at 00:59:26 UTC, deadalnix wrote:
> Now this is wrong. A new n variable is created at each loop 
> iteration, this isn't the same n. It's easy to convince oneself 
> that this is the case: n can be made immutable and the code 
> still compiles, which is evidence that the semantic is that 
> each loop iteration has a new n variable.

Yes, that is the semantics I would expect. Note the complication 
when vars from multiple scopes are captured:

```d
int i = 1;
dgList ~= { writeln(i); };

while (i < 4) {
    immutable int n = i++;
    dgList ~= { writeln(i, " ", n); };
}
```
Expected:
4
4 1
4 2
4 3


That would require an implementation like this:
```d
static struct __C0
{
     int i;
     void call() { writeln(i); }
}

auto c0 = new __C0(1);
dgList ~= &c0.call;

while (c0.i < 4) {
    static struct __C1 {
       __C0* c0;
       immutable int n;
       void call() { writeln(c0.i, " ", n); }
    }

    dgList ~= &(new __C1(c0, c0.i++)).call;
}
```


More information about the Digitalmars-d mailing list