Search code examples
c#arrayspost-incrementpre-increment

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


Solution

  • 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