confusing (buggy?) closure behaviour

Zoran Isailovski dmd.zoc at spamgourmet.com
Fri Dec 12 08:32:03 PST 2008


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???
-------------- next part --------------
A non-text attachment was scrubbed...
Name: closures01.d
Type: application/octet-stream
Size: 1265 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20081212/da33e77c/attachment.obj>


More information about the Digitalmars-d-learn mailing list