Bug 18201 – Compiler bug in lexical closures

Status
RESOLVED
Resolution
DUPLICATE
Severity
major
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2018-01-06T17:32:18Z
Last change time
2018-01-06T23:40:27Z
Assigned to
No Owner
Creator
Alexandru Razvan Caciulescu

Comments

Comment #0 by alexandru.razvan.c — 2018-01-06T17:32:18Z
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 ... The equivalent C# code: 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 ...
Comment #1 by ag0aep6g — 2018-01-06T23:40:27Z
*** This issue has been marked as a duplicate of issue 2043 ***