Multiple assignment

Dan Olson zans.is.for.cans at yahoo.com
Sat Feb 26 11:18:20 PST 2011


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.

Dan


More information about the Digitalmars-d-learn mailing list