In C, what is the difference between using ++i
and i++
, and which should be used in the incrementation block of a for
loop?
++i
(Prefix operation): Increments and then assigns the value
(eg): int i = 5
, int b = ++i
In this case, 6 is assigned to b first and then increments to 7 and so on.
i++
(Postfix operation): Assigns and then increments the value
(eg): int i = 5
, int b = i++
In this case, 5 is assigned to b first and then increments to 6 and so on.
Incase of for loop: i++
is mostly used because, normally we use the starting value of i
before incrementing in for loop. But depending on your program logic it may vary.