I’m well aware that in C++
int someValue = i++;
array[i++] = otherValue;
has different effect compared to
int someValue = ++i;
array[++i] = otherValue;
but every once in a while I see statements with prefix increment in for-loops or just by their own:
for( int i = 0; i < count; ++i ) {
//do stuff
}
or
for( int i = 0; i < count; ) {
//do some stuff;
if( condition ) {
++i;
} else {
i += 4;
}
}
In the latter two cases the ++i looks like an attempt to produce smarty-looking code. Am I overseeing something? Is there a reason to use ++i instead of i++ in the latter two cases?
If we ignore force of habit, ‘++i’ is a simpler operation conceptually: It simply adds one to the value of i, and then uses it.
i++on the other hand, is “take the original value ofi, store it as a temporary, add one toi, and then return the temporary”. It requires us to keep the old value around even afterihas been updated.And as Konrad Rudolph showed, there can be performance costs to using
i++with user-defined types.So the question is, why not always just default to
++i?If you have no reason to use `i++´, why do it? Why would you default to the operation which is more complicated to reason about, and may be slower to execute?