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 a while()
loop:
for (INITIALIZER; CONDITION; OPERATION) {
do_stuff();
}
Can be written:
INITIALIZER;
while(CONDITION) {
do_stuff();
OPERATION;
}
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 increment i
and ignore the result. The new value of i
is not tested until the next iteration begins, at the top of the loop.
Edit: Thanks to Jason for pointing out that this for()
to while()
equivalence does not hold if the loop contains control statements (such as continue
) that would prevent OPERATION
from being executed in a while()
loop. OPERATION
is always executed just before the next iteration of a for()
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 the while()
. It made for a fascinating interview, but we didn't make an offer!
Hope that helps!