Evaluation order

Michiel Helvensteijn m.helvensteijn.remove at gmail.com
Wed Feb 24 13:03:40 PST 2010


bearophile wrote:

> 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.

I would prefer that the evaluation order be officially specified as
non-deterministic. That is, the standard guarantees that the observable
behavior be equivalent to some sequential order of evaluation.

For example:

void f() {}
f(x = 1, x = 2);
assert(x == 1 || x == 2);

It's the same as what C does, just more formally defined. The compiler is
free to choose the most efficient implementation that satisfies the
contract.

This is because to me, any asymmetric choice of evaluation order would be
arbitrary and wrong. What's so special about left-to-right?

-- 
Michiel Helvensteijn




More information about the Digitalmars-d mailing list