weird behavior returning delegate
Sean Kelly
sean at f4.ca
Sat Jul 1 09:51:02 PDT 2006
Carlos Santander wrote:
> This code, with DMD 0.162 on Windows:
>
> //-----------------------
> T delegate (T) acc (T) (T n)
> {
> return (T i) { return n += i; };
> }
>
> void foo ()
> {
> auto acc1 = acc (4);
> assert (5 == acc1 (1), "5 != 5");
> assert (7 == acc1 (2), "7 != 7");
>
> auto acc2 = acc (10);
> assert (11 == acc2 (1), "11 != 11");
> assert (12 == acc2 (1), "12 != 12");
>
> assert (10 == acc1 (3), "10 != 10"); // 16
> assert (20 == acc2 (8), "20 != 20");
> }
>
> import std.stdio;
>
> void bar ()
> {
> auto acc1 = acc (4);
> writefln (" 5 == %s", acc1 (1));
> writefln (" 7 == %s", acc1 (2));
>
> auto acc2 = acc (10);
> writefln ("11 == %s", acc2 (1));
> writefln ("12 == %s", acc2 (1));
>
> writefln ("10 == %s", acc1 (3));
> writefln ("20 == %s", acc2 (8));
> writefln ();
> }
>
> void main()
> {
> bar ();
> foo ();
> }
> //-----------------------
>
> Produces this:
>
> 5 == 5
> 7 == 10
> 11 == 11
> 12 == 9
> 10 == 13
> 20 == 17
>
> Error: AssertError Failure test.d(16) 10 != 10
>
> I think the assert failing is somewhat expected (stack frame no longer
> available), but how can the previous asserts work when the values shown
> with writefln are not the ones expected, or supposedly asserting correctly?
It's because you're using one function to do the asserts and another to
print results, so the values returned from acc1 and acc2 may be
different. I combined the two cases by storing the result in a number
then performing the assert, etc, and the errors corresponded with what
was displayed.
Sean
More information about the Digitalmars-d
mailing list