loop's counter i as I++ vs. i+1 as position in an array

前端 未结 7 1530
甜味超标
甜味超标 2021-01-13 23:25

I\'ve made a loop with i as it\'s counter variable.
Inside that loop I\'m comparing cells of an array.
I\'m wondering what\'s the difference between array[i++] (or a

7条回答
  •  日久生厌
    2021-01-13 23:41

    • array[i++] will evaluate array[i] and increment i.
    • array[++i] will increment i and then evaluate array[i] (so it gives you the next element)
    • array[i+1] will give you the next element without incrementing i

    Personally I try to avoid using side-effects like this - it means when I read the code later, I always have to slow down to make sure I get everything in the right order.

    If you're already in a loop which is incrementing i, then incrementing i in the array access expression as well would mean that each loop iteration would increment i twice.

提交回复
热议问题