Home > Software design >  increment array index left side of assignment operator
increment array index left side of assignment operator

Time:11-03

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

CodePudding user response:

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.

  • Related