Why ++i is often better than i++ (pre-increment vs. post-increment)
Published in · 2 min read · Nov 6, 2019
--
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
, i++
, and even i = i + 1
.
In this article, I will cover two methods of adding 1, ++i
, and i++
, and explain why ++i
may be better than i++
in most situations.
The i++
method, or post-increment, is the most common way.
In psuedocode, the post-increment operator looks roughly as follows for a variable i
:
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 i
.
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…