If you’ve written a for-loop before, then you have almost definitely used
i++ before to increment your loop variable.
However, have you ever thought about why you choose to do it like that?
Clearly, the end result of
i++ is that
i is one higher than it was before — which is what we want. But, there are many ways to accomplish this, such as
i++, and even
i = i + 1.
In this article, I will cover two methods of adding 1,
i++, and explain why
++i may be better than
i++ in most situations.
i++ method, or post-increment, is the most common way.
In psuedocode, the post-increment operator looks roughly as follows for a variable
int j = i; i = i + 1; return j;
Since the post-increment operator has to return the original value of
i, and not the incremented value
i + 1, it has to store the old version of
This means that it typically needlessly uses additional memory to store that value, since, in most cases, we do not actually use the old version of
i, and it is simply discarded.
++i method, or pre-increment, is much less common and is typically used by older programmers in languages such as C and C++.
In psuedocode, the pre-increment operator looks roughly like this for a variable
i = i + 1; return i;
Notably, here, we do not have to save the old value of
i — we can simply add to it and return. This aligns much better with the typical use-case in a for-loop, since we rarely need the old value of
i in that context.
After seeing the difference between post-increment and pre-increment, one might notice that, since the cached value of
i is never used in post-increment, the compiler will just optimize that line away, making the two operators equivalent.
This is most likely true for primitive types, such as an integer.
However, for more complex types, such as user-defined types or iterators with the
+ operation overloaded, the compiler may not be able to safely optimize the caching operation.
So, it seems that in most cases, the pre-increment operator is better than, or equal to, the post-increment operator, as long as you do not need the previous value of whatever you are incrementing.