Multiple assignment

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 26 17:09:32 PST 2011


On Saturday 26 February 2011 11:18:20 Dan Olson wrote:
> Jonathan M Davis <jmdavisProg at gmx.com> writes:
> > On Friday, February 25, 2011 17:31:36 Ali Çehreli wrote:
> >> On 02/25/2011 05:09 PM, bearophile wrote:
> >>  >      int j;
> >>  >      int[2] y;
> >>  >      y[j] = j = 1;
> >> 
> >> I think that's undefined behavior in C and C++. It is not defined
> >> whether j's previous or past value is used in y[j].
> >> 
> >> I would expect the situation be the same in D.
> > 
> > No, that should be perfectly defined. What's undefined is when you do
> > something like func(j, y[j]). The evaluation order of the function
> > arguments is undefined.  However, the evaluation order when dealing
> > with an assignment should be defined.  I _could_ be wrong about that,
> > but there's no question that the assignments themselves are guaranteed
> > to be done in right-to-left order.
> > 
> > - Jonathan M Davis
> 
> Java made assignment well defined by saying:
>   First evaluate the left-hand-side to determine a variable to assign to.
>   Then evaluate the right-hand-side for the value.
> 
> If the right-hand-side is another assignment, repeat...
> 
> So given:
> int i = 0;
> int[] a = new int[4];
> 
> a[i++] = a[i+=2] = i = 9;
> 
> You are can depend on getting:
> 
> i = 9
> a = [9, 0, 0, 9]
> 
> 
> D today on windows yields the same output.  Will the D language spec
> make this the define behavior too?  I noticed that
> http://www.digitalmars.com/d/2.0/expression.html currently says it is
> implementation defined.  The example given is:
> 
> i = i++;
> 
> None of this is stuff you'd normally want to write unless entering an
> obfuscated programming contest, but Java's rules say if i = 42, 'i' will
> end up still being 42.

The assignment order is well-defined in both C++ an D, but the order of 
evaluation of the expressions is not. Now, Walter has stated in the past that he 
intends to make the order of evaluation of expressions defined in D at some 
point, but he hasn't done it yet, so right now it's still undefined.

Regardless, it doesn't really hurt you any to avoid ambiguous expressions like 
these and since there _are_ languages which leave ther evaluation order as 
undefined, it's probably a good habit to get into to _not_ write such ambiguous 
expressions.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list