C# seems to preserve left-hand value of an assignment statement

Consider this weird piece of code:

  int[] a = new int[] { 0, 1, 2 };

  int i = 2; // Point it to the last item of array

  // Set the value of array indexed by i while
  // changing the value of i
  a[ i ] = ++i + ++i;


The code above will not cause an array's bounds overflow.

The value of i was incremented (++i) then added to its another incremented value (+ ++i),
but for some reason the left hand part seems to remember the original value of i.

I didn't know that Big Smile

Published 08-03-2008 8:52 PM by cvega

Comments

# re: C# seems to preserve left-hand value of an assignment statement

Monday, August 04, 2008 1:29 AM by jop

The 2nd line: (int i=2; // Point it to the last item of array) does not make sense. Html quoting error perhaps?

And it gave me the expected results: a = 3 + 4 which is 7.

# re: C# seems to preserve left-hand value of an assignment statement

Monday, August 04, 2008 2:20 AM by cvega

Sorry, the line should be:

a[ i ] = ++i + ++i

The BBCode is evaluating the code enclosed with square bracket.

# re: C# seems to preserve left-hand value of an assignment statement

Monday, August 04, 2008 2:54 AM by jop

Ah ok. That behaviour is defined on the language specs. Evaluation happens left to right.

   a[ i ] = ++i + ++i

evaluate the first i to become:

   a[ 2 ] = ++i + ++i

then the next i becomes:

   a[ 2 ] = (2+1) + ++i

and finally:

   a[ 2 ] = 3 + (3+1)

C does differently - which leaves a lot of things implementation defined.

# re: C# seems to preserve left-hand value of an assignment statement

Monday, August 04, 2008 10:41 PM by cvega

That means that left-associative puts equal ( = ) in highest order?

int i = 2;

a[ i ] *= i + i;

is being evaluated as:

a[ 2 ] *= i + i;

a[ 2 ] *= 2 + 2;

a[ 2 ] *= 6

While we know that multiplication (*)is higher in order-of-precedence from addition (+).

This makes sense only if assignment (=) has the highest order-of-precedence than all the other operators.

# re: C# seems to preserve left-hand value of an assignment statement

Tuesday, August 05, 2008 12:34 AM by jop

*= is an assignment operator and it is just one operator. Assignment operators have the lowest precedence. That's why they are resolved the last.

# re: C# seems to preserve left-hand value of an assignment statement

Tuesday, August 05, 2008 12:38 AM by jop

another thing: assignment operators are right-associative. That is why you can chain the assignment operator:

a = b = c = 0; // set a, b, and c to zero.