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

前端 未结 7 1471
甜味超标
甜味超标 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:29

    • i++: increase the value stored in i by one, and return the old value.
    • ++i: increase the value stored in i by one, and return the new value.
    • i+1: return the sum of i and 1, without changing the value stored in i

    Now consider what happens if, as I suspect, you have code that looks like

    for ( i = 0; i < something; i++ )
    {
       dosomething(i++);
    }
    

    the values of i passed to dosomething() will be 0 2 4 8 . .

    since every iteration of the loop, i is incremented once in the for() line and once in the dosomething() line, and the dosomething() call is given the value i had before it was incremented. If the behaviour actually desired is for dosomething() to be called with the sequence 1 2 3 4 . . then you need to avoid updating i with the result of adding 1 to it in the loop body: for ( i = 0; i < something; i++ ) { dosomething(i+1); }

    or even

    for ( i = 1; i < (something+1); i++ )
    {
       dosomething(i);
    }
    

提交回复
热议问题