Expression evaluation order

monarch_dodra monarchdodra at gmail.com
Thu Jun 13 23:14:50 PDT 2013


On Friday, 14 June 2013 at 00:13:37 UTC, Jonathan M Davis wrote:
> On Friday, June 14, 2013 02:02:23 David Nadlinger wrote:
>> On Thursday, 13 June 2013 at 23:25:42 UTC, Jonathan M Davis 
>> wrote:
>> > Walter has expressed a desire in the past to make it so that 
>> > D
>> > requires that
>> > the evaluation order of arguments be left-to-right in order 
>> > to
>> > avoid bugs, and
>> > while these aren't exactly function arguments, …
>> 
>> Actually, behind the scenes all three are arguments to *one*
>> function call: the druntime array op implementation.
>> 
>> Anyway, my question was mainly about the assignment operator,
>> which is obviously not expected to behave lexically 
>> left-to-right
>> by that test case.
>
> I don't see how the assignment operator could possibly work 
> left-to-right

What do you mean? assignment requires two arguments: the 
*reference* of lhs, and value/reference or rhs. Regardless of if 
lhs is a value or expression, the compiler still needs to know 
*where* to assign to.

I don't see any reasons why the compiler couldn't choose lhs 
first instead.

*as* a matter of fact, that's how gcc does it for C++:

//----
int main()
{
     int i = 0;
     ++i = ++i;
     assert(i == 2); //passes
}
//----

Left to right
First, evaluate lhs: i has the value 1.
then evaluate rhs, which will now have the value 2.
assign 2 to i.
* i == 2 *

right to left:
First, evalutate rhs: i has the value 1, an rhs 1.
Evaluate lhs: i is now 2.
But then assign rhs (1) to lhs.
* i == 1 *

So yeah, left to right evaluation is completely coherent, and a 
valid scheme.

Heck, you'll notice this *also* passes with DMD, so dmd *also* 
evaluates opEqual left to right.

So I guess this "surprising behavior" is the evaluation order we 
want to enforce?

---------
I remember the discussion:
http://forum.dlang.org/thread/bniaxycuguviwfdtojzf@forum.dlang.org

For the record, I don't remember there being a consensus... at 
all...
There were 3.5 positions:
1) left to right evaluation
2) right to left evaluation
3) specifically unspecified
   3.5) error when compiler sees ambiguity

I'm personally in favor of 3, with some 3.5 as a warning. 
Evaluation order, even when defined, remains obscure once 
associative operations come into play, and still bite you in the 
ass anyways, so I don't see anything good out of forcing it one 
way or the other anyways.


More information about the Digitalmars-d mailing list