Chained method argument evaluation order

Jarrett Billingsley kb3ctd2 at yahoo.com
Wed Jan 16 07:01:55 PST 2008


Something tells me this was discussed before, but sheesh..

int a() { Stdout.formatln("A"); return 1; }
int b() { Stdout.formatln("B"); return 2; }

struct S
{
    S* chain(int x)
    {
        Stdout.formatln("{}", x);
        return this;
    }
}

void main()
{
    S s;
    s.chain(a()).chain(b());
}

This prints the following compiled with DMDWin:

B
A
1
2

Notice that the chained methods are called in the right order, but that 
their arguments -- even though they're in different function calls!! -- are 
evaluated in _reverse_ order, and _before_ any of the chained methods are 
called.

I really wouldn't have expected this.  I _would_ have expected

A
1
B
2

But the compiler must be being clever here, for some reason.

Should this kind of thing be documented, specified, implementation-dependent 
etc.?  Because I would have expected the chained call above to basically be 
evaluated as:

auto t = s.chain(a());
t.chain(b());

which gives the expected output above. 





More information about the Digitalmars-d mailing list