Originally posted by Aafreen Moinuddin:
how does a postfix increment operator differ from prefix increment operator in a loop?
The best way to understand expressions ++i and i++ is to realize that there are two important but separate aspects of any expression:
1. its value
2. its side effect
Both ++i and i++ have the same side effect -- incrementing the value of variable i -- but they have different values. Sometimes the value of an expression is ignored, for example, when you add() to a collection like this:
col.add(object);
add returns true/false to indicate whether or not the collection was changed by the call. If you don't need to examine that returned value you can ignore it. Similarily, the third expression in the for statement is there purely for its side effect -- its value is discarded, so these two loops are equivalent, and which way you choose to write it is not imporant:
for(...; ...; ++i) {...}
for(...; ...; i++) {...}