Difference between arr[0]++ and ++arr[0]
In C#, is there a difference between the code (all in one statement, not part of a larger one) arr[0]++;
and ++arr[0];
I fully understand, that in C / C++ / Objective-C, that this would开发者_JAVA百科 not do the same thing, first case would get the value at arr's 0th index and increment that value by one, while the second one, increases the pointer value of arr, and does nothing to it's 0th position (same as arr[1]; arr++;
).
Thanks to sth, he has reminded me that this is the same in C# and C / C++ / Obj-C.
However, is there a difference between the two statements in C#?
arr[0]++
returns the value of the first element of arr
, then increments it.
++arr[0]
increments the value of the first element of arr
, then returns it
The difference only matters if you're using this as part of a longer instruction. For instance :
arr[0] = 42;
int x = arr[0]++; // x is now 42, arr[0] is now 43
Is not the same as:
arr[0] = 42;
int x = ++arr[0]; // x is now 43, arr[0] is now 43
If it is a single statement there is no difference.
++x increments and then returns while x++ returns the value of x and then increments ! But if there is no one to receive the value, its all the same.
An optimizing compiler should generate the same code if that statement exists by itself, but when you're using the value you're modifying inline, post-increment can require making a copy (so you can work with the old value), which can be expensive if the array is of a type that has an expensive copy constructor.
精彩评论