views:

115

answers:

4

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 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#?

+1  A: 

If it is a single statement there is no difference.

Mark Byers
That was fast, thanks!
Richard J. Ross III
+10  A: 

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
Thomas Levesque
Yes, but that means that there is no difference if it is a singe statement, right?
Richard J. Ross III
@Richard, see my edit
Thomas Levesque
@Richard: Right
abatishchev
+1  A: 

++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.

mumtaz
A: 

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.

Chris