confusing (buggy?) closure behaviour

"Jérôme M. Berger" jeberger at free.fr
Fri Dec 12 13:47:04 PST 2008


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Zoran Isailovski wrote:
> I'm an experienced C#, Java and Python programmer, and have employed closures (and C# delegates) upon numerous occasions. While experimenting with D closures and delegates, I was stroke by a phenomenon I cannot explain. Here's the code:
> 
> module closures01;
> 
> import std.stdio;
> 
> alias int delegate(int arg) Handler;
> 
> Handler incBy(int n)
> {
> 	return delegate(int arg){ return arg + n; };
> }
> 
> Handler mulBy(int n)
> {
> 	return delegate(int arg){ return arg * n; };
> }
> 
> void test1()
> {
> 	writefln("\ntest1:\n----------------------------------------");
> 	int x = 10, y;
> 	y = mulBy(3)(x); writefln("%d * 3 -> %d", x, y);
> 	y = mulBy(4)(x); writefln("%d * 4 -> %d", x, y);
> 	y = incBy(2)(x); writefln("%d + 2 -> %d", x, y);
> }
> 
> void test2()
> {
> 	writefln("\ntest2:\n----------------------------------------");
> 	int x = 10, y;
> 	Handler times3 = mulBy(3);
> 	Handler times4 = mulBy(4);
> 	Handler plus2 = incBy(2);
> 	y = times3(x); writefln("%d * 3 -> %d", x, y);
> 	y = times4(x); writefln("%d * 4 -> %d", x, y);
> 	y = plus2(x); writefln("%d + 2 -> %d", x, y);
> }
> 
> public void run()
> {
> 	test1();
> 	test2();
> }
> 
> /* **************************************** *
>  * Compiled with: Digital Mars D Compiler v1.030
>  *
>  * (Unexplainable) program output:
>  
> test1:
> ----------------------------------------
> 10 * 3 -> 30
> 10 * 4 -> 40
> 10 + 2 -> 12
> 
> test2:
> ----------------------------------------
> 10 * 3 -> 20
> 10 * 4 -> 42846880
> 10 + 2 -> 4284698
> 
> * **************************************** */
> 
> What goes wrong???

	In both cases, when your delegate gets called, the corresponding
stack frame is invalid. However, in test1, the stack data is still
intact when the delegate is called, whereas in test2 it has been
overwritten by the calls to mulBy(4), incBy(2) and writefln.

		Jerome
- --
mailto:jeberger at free.fr
http://jeberger.free.fr
Jabber: jeberger at jabber.fr
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAklC29gACgkQd0kWM4JG3k/w9ACdFsvzgE98G+HBuhQRhwig0ZTg
X+gAn1HVbECBvkiqrUMju3btW2fBGjtx
=6ae5
-----END PGP SIGNATURE-----


More information about the Digitalmars-d-learn mailing list