++i or i++ in for loops ?? [duplicate]
Solution 1:
++i
is slightly more efficient due to its semantics:
++i; // Fetch i, increment it, and return it
i++; // Fetch i, copy it, increment i, return copy
For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the loop body doesn't contain much work).
As an example, consider the following loop using a theoretical BigInteger class providing arbitrary precision integers (and thus some sort of vector-like internals):
std::vector<BigInteger> vec;
for (BigInteger i = 0; i < 99999999L; i++) {
vec.push_back(i);
}
That i++ operation includes copy construction (i.e. operator new, digit-by-digit copy) and destruction (operator delete) for a loop that won't do anything more than essentially make one more copy of the index object. Essentially you've doubled the work to be done (and increased memory fragmentation most likely) by simply using the postfix increment where prefix would have been sufficient.
Solution 2:
For integers, there is no difference between pre- and post-increment.
If i
is an object of a non-trivial class, then ++i
is generally preferred, because the object is modified and then evaluated, whereas i++
modifies after evaluation, so requires a copy to be made.
Solution 3:
++i
is a pre-increment; i++
is post-increment.
The downside of post-increment is that it generates an extra value; it returns a copy of the old value while modifying i
. Thus, you should avoid it when possible.