www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 18201] New: Compiler bug in lexical closures

https://issues.dlang.org/show_bug.cgi?id=18201

          Issue ID: 18201
           Summary: Compiler bug in lexical closures
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: major
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: alexandru.razvan.c gmail.com

Given the code:

import std.stdio;

void main(){
    void delegate() fns[];
    for (int i = 0; i < 10; i++){
        int a = i;
        fns ~= (){
            writeln(a);
        };
    }
    for (int i = 0; i < 10; i++){
        fns[i]();
    }
}

This will print out:
9
9
9
9
...



using System;
using System.Collections.Generic;

public class Test
{
        public static void Main()
        {
                List<Action> fns = new List<Action>();
                for(int i = 0; i < 10; i++){
                        int a = i;
                        fns.Add(() => Console.WriteLine("{0} {1}", i, a));
                }
                for(int i = 0; i< 10; i++){
                        fns[i]();
                }
        }
}

This prints:
10 0
10 1
10 2
10 3
10 4
...

--
Jan 06 2018