"a[++i] = i" vs "a[i] = ++i"

Ali Çehreli acehreli at yahoo.com
Fri Dec 20 14:37:30 PST 2013


On 12/20/2013 02:29 PM, Ivan Smirnov wrote:> I was wondering if this 
behavior is actually documented anywhere? Let's
 > say we want to increment i and store the new value at the index equal to
 > the new (incremented) value.
 >
 >      int[int] a;
 >      int i = 1;
 >      a[++i] = i;
 >      writeln(a);
 >      a[i] = ++i;
 >      writeln(a);
 >
 >>> [2:2]
 >>> [2:2, 3:3]
 >
 > If any, I would expect it to work for either one of lines but not both?
 >
 > What is interesting, if you compile the same in C (I used clang), you
 > get a "warning: unsequenced modification

That is a roundabout way of saying "the assignment operator does not 
define a sequence point". :p

 > and access to 'i'" on both
 > lines and the answer is (as I would initially except)
 >
 >>> [2:1]
 >>> [2:1, 3:3]

Well, regardless of one's expectations, that is one outcome of 
unspecified behavior. :)

Although D is less vocal on these topics it is the same as C and C++: 
The evaluation order is unspecified. I've read before that Walter wants 
to eventually define such evaluation orders but it is not specified yet.

Ali



More information about the Digitalmars-d-learn mailing list