This question already has an answer here:
- Difference between i++ and ++i in a loop? 21 answers
The following for loops produce identical results even though one uses post increment and the other pre-increment.
Here is the code:
for(i=0; i<5; i++) {
printf("%d", i);
}
for(i=0; i<5; ++i) {
printf("%d", i);
}
I get the same output for both 'for' loops. Am I missing something?
If you wrote it like this then it would matter :
Would iterate once more than if written like this :
Because in either case the increment is done after the body of the loop and thus doesn't affect any of the calculations of the loop. If the compiler is stupid, it might be slightly less efficient to use post-increment (because normally it needs to keep a copy of the pre value for later use), but I would expect any differences to be optimized away in this case.
It might be handy to think of how the for loop is implemented, essentially translated into a set of assignments, tests, and branch instructions. In pseudo-code the pre-increment would look like:
Post-increment would have at least another step, but it would be trivial to optimize away
Both i++ and ++i is executed after printf("%d", i) is executed at each time, so there's no difference.
The result of your code will be the same. The reason is that the two incrementation operations can be seen as two distinct function calls. Both functions cause an incrementation of the variable, and only their return values are different. In this case, the return value is just thrown away, which means that there's no distinguishable difference in the output.
However, under the hood there's a difference: The post-incrementation
i++
needs to create a temporary variable to store the original value ofi
, then performs the incrementation and returns the temporary variable. The pre-incrementation++i
doesn't create a temporary variable. Sure, any decent optimization setting should be able to optimize this away when the object is something simple like anint
, but remember that the ++-operators are overloaded in more complicated classes like iterators. Since the two overloaded methods might have different operations (one might want to output "Hey, I'm pre-incremented!" to stdout for example) the compiler can't tell whether the methods are equivalent when the return value isn't used (basically because such a compiler would solve the unsolvable halting problem), it needs to use the more expensive post-incrementation version if you writemyiterator++
.Three reasons why you should pre-increment:
This is one of my favorite interview questions. I'll explain the answer first, and then tell you why I like the question.
Solution:
The answer is that both snippets print the numbers from 0 to 4, inclusive. This is because a
for()
loop is generally equivalent to awhile()
loop:Can be written:
You can see that the OPERATION is always done at the bottom of the loop. In this form, it should be clear that
i++
and++i
will have the same effect: they'll both incrementi
and ignore the result. The new value ofi
is not tested until the next iteration begins, at the top of the loop.Edit: Thanks to Jason for pointing out that this
for()
towhile()
equivalence does not hold if the loop contains control statements (such ascontinue
) that would preventOPERATION
from being executed in awhile()
loop.OPERATION
is always executed just before the next iteration of afor()
loop.Why it's a Good Interview Question
First of all, it takes only a minute or two if a candidate tells the the correct answer immediately, so we can move right on to the next question.
But surprisingly (to me), many candidates tell me the loop with the post-increment will print the numbers from 0 to 4, and the pre-increment loop will print 0 to 5, or 1 to 5. They usually explain the difference between pre- and post-incrementing correctly, but they misunderstand the mechanics of the
for()
loop.In that case, I ask them to rewrite the loop using
while()
, and this really gives me a good idea of their thought processes. And that's why I ask the question in the first place: I want to know how they approach a problem, and how they proceed when I cast doubt on the way their world works.At this point, most candidates realize their error and find the correct answer. But I had one who insisted his original answer was right, then changed the way he translated the
for()
to thewhile()
. It made for a fascinating interview, but we didn't make an offer!Hope that helps!
After evaluating
i++
or++i
, the new value ofi
will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.++i
incrementsi
and evaluates to the new value ofi
.i++
evaluates to the old value ofi
, and incrementsi
.The reason this doesn't matter in a for loop is that the flow of control works roughly like this:
Because (1) and (4) are decoupled, either pre- or post-increment can be used.