Closure capture loop variables

Freddy via Digitalmars-d digitalmars-d at puremagic.com
Wed Apr 29 18:16:19 PDT 2015


I understand that
----
import std.stdio;
void main(){
	int delegate() func;
	foreach(i;0..10){
		if(i==5){
			func= () => i;
		}
	}
	writeln(func());//9
}
----
captures the loop variable,but why does
----
import std.stdio;

void main(){
	int delegate() func;
	foreach(i;0..10){
		auto copy=i;
		if(i==5){
			func= () => copy;
		}
	}
	writeln(func());//should be 5
}

----
still print 9.


More information about the Digitalmars-d mailing list