Order of operations when working with array index
Consider this loop:
int[] myArray = new int[10];
int myIndex = 0;
for (int i = 0; i < 10; i++开发者_开发知识库)
{
myArray[myIndex++] = myIndex;
Console.WriteLine(myArray[i]);
}
This yields:
1
2
3
...
Because myIndex is post-incremented, and the right side is evaluated first, shouldn't the array index 0 contain 0?
Can someone explain this order-of-operations misunderstanding for me?
The right side isn't necessarily evaluated first. Similar to:
foo.Bar.Baz = a + b;
In the above code, foo.Bar
is evaluated first, then a + b
, then the set_Baz
method is called to set the Baz property to whatever is evaluated on the right.
So in your code, if you break it into pieces, it looks like this:
var index = i;
// post-incremented in the original code means this comes after the line above,
// but not after the line below it.
i += 1;
myArray[index] = i;
first run:
myArray[myIndex++] = myIndex;
* *
| |
zero one
myIndex++
gets executed after myArray[myIndex++]
, but any subsequent calls with have the already incremented variable.
The myIndex++ is executing before the value is being set because the array index takes precident so it knows what array index to set the value to.
The...
myArray[myIndex++] = myIndex;
...is equivalend to...
int tmp = myIndex;
++myIndex;
myArray[tmp] = myIndex;
The myIndex++
is evaluated first, followed by the left side and finally the assign operator, according to precedence
精彩评论