简体   繁体   中英

increment array index left side of assignment operator

int[] array = new int[]{ 1, 2, 3 };
int i = 1;
array[i++] = array[i]+5;
   
var result = string.Join(",", array);
Console.WriteLine(result);

can you explain how to work 3rd row? I mean why the answer is 1,8,3

Your code can be translated to:

int[] array = new int[]{ 1, 2, 3 };
int i = 1;
array[1] = array[2]+5;

because i++ means: use the old value of i and afterwards increment it by 1. So at the assignment array[i]+5 , i will have the new value 2.

If you instead use ++i instead it will "translate" to:

array[2] = array[2]+5;

because ++i means: increment it before you use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM