On Thursday, 29 March 2018 at 20:05:35 UTC, ag0aep6g wrote:
On Thursday, 29 March 2018 at 19:02:51 UTC, kdevel wrote:
On Thursday, 29 March 2018 at 15:16:07 UTC, Ivan Kazmenko wrote:
[...]
        int delegate () [] guns;
        foreach (i; 0..2) guns ~= () => i;
        foreach (i; 0..2) writeln (guns[i] ());  // 1 and 1, why?

Isn't this undefined behavior? The first loop variable named "i" already went out of scope when the delegate is invoked.

Not undefined behavior.

What is the lifetime of the first loop's variable i? What about this example:

``` bug2.d
import std.stdio;

void main ()
{
   int delegate () [] dg;
   foreach (i; 0..2) {
      int *j;
      if (i == 0) {
         auto k = i;
         j = &k;
      }
      else {
         auto l = i;
         j = &l;
      }
      dg ~= () => *j;
   }
   foreach (p; dg)
      p ().writeln;
}
```

Reply via email to