Evaluation order
bearophile
bearophileHUGS at lycos.com
Wed Feb 24 09:42:02 PST 2010
(I discuss such topics here because I don't know where else I can)
I have seen a recent change:
http://dsource.org/projects/dmd/changeset/399
I guess it's something related to specifying an evaluation order in D in function calls like bar() of main():
import std.stdio: writeln;
import std.string: format;
class Obj {
int x;
this(int xx) { x = xx; }
string member() { return format("member ", x); }
}
Obj foo() {
return new Obj(2);
}
void bar(string s, Obj o2) {
writeln("bar ", s, " ", o2.x);
}
void main() {
Obj o = new Obj(1);
bar(o.member(), o=foo());
}
C specifications do not define the order of evaluation for function arguments. It can be left-to-right, right-to-left or anything else and is unspecified. Thus any code which relies on this order of evaluation is not portable.
D can solve this problem as I think Java has done, just specifying it, and forcing the compiler to produce hypothetically a bit less efficient code in some situations.
Another strategy to solve this problem that's possible in D (and not possible in C) is to allow only pure expressions inside function calls. So in a function call you can put pure expressions like x+5 or calls to pure functions. And then the D compiler is free to leave unspecified the order of evaluation of function arguments.
Bye,
bearophile
More information about the Digitalmars-d
mailing list