Is there a difference in ++i
and i++
in a for
loop? Is it simply a syntax thing?
Yes, there is. The difference is in the return value. The return value of "++i" will be the value after incrementing i. The return of "i++" will be the value before incrementing. This means that code that looks like the following:
int a = 0;
int b = ++a; // a is incremented and the result after incrementing is saved to b.
int c = a++; // a is incremented again and the result before incremening is saved to c.
Therefore, a would be 2, and b and c would each be 1.
I could rewrite the code like this:
int a = 0;
// ++a;
a = a + 1; // incrementing first.
b = a; // setting second.
// a++;
c = a; // setting first.
a = a + 1; // incrementing second.