Is there a difference in ++i
and i++
in a for
loop? Is it simply a syntax thing?
There is no difference if you are not using the value after increment in the loop.
for (int i = 0; i < 4; ++i){
cout<
Both the loops will print 0123.
But the difference comes when you uses the value after increment/decrement in your loop as below:
Pre Increment Loop:
for (int i = 0,k=0; i < 4; k=++i){
cout<
Output: 0 0 1 1 2 2 3 3
Post Increment Loop:
for (int i = 0, k=0; i < 4; k=i++){
cout<
Output: 0 0 1 0 2 1 3 2
I hope the difference is clear by comparing the output. Point to note here is the increment/decrement is always performed at the end of the for loop and hence the results can be explained.