0

can you do array[i]++?

Is it the same as array[i] = array[i] + 1?

If not, why not? Is it something to do with how primitives vs references are treated?

NcXNaV
  • 1,657
  • 4
  • 14
  • 23
Qrow Saki
  • 932
  • 8
  • 19

1 Answers1

1

There's a slight difference: postfix vs prefix increment operator

  1. If you use array[i]++, the old value will be used for the calculation and the value of i will be increased by 1 afterwards.

  2. For array[i] = array[i] + 1, it's the opposite: i will first be incremented and only then the calculation will take place.

For more details, check this out.

NcXNaV
  • 1,657
  • 4
  • 14
  • 23
  • are you saying array[i]++ wouldn't actually reflect a change of +1 in the array since the old value is stored, not the new one? – Qrow Saki Jul 18 '21 at 06:07
  • 1
    Both will reflect a change of +1. The only difference is `order of operations` between the `increment of the variable` and the `value the operator returns`. – NcXNaV Jul 18 '21 at 06:10
  • `array[i]++` only increments `array[i]` after the whole instruction it appears in is evaluated. So suppose in a loop, if you have `array[i] = 1` and `array[i]++`, it will wait until current iteration done, before increment the value of array[i] by `1`. So when you print it, it will still give `1`, but when next iteration start, without even increment `array[i]` it again, it will give you `2`. On the other hand, if you have `array[i] = 1` and `array[i] = array[i] + 1`, it will directly increment it, and print `2`. Hope this clarifies it. – NcXNaV Jul 18 '21 at 06:25