Programming Fundamentals · Interview question

What's the difference between for (int i = 0; ...; i++) and for (int i = 0; ...; ++i)?

A strong answer

For the loop, none. In the update slot of a for header the expression's result is discarded and only the side effect matters, so i++ and ++i increment identically and produce the same machine code on any modern compiler, even at -O0. The distinction is real only where the value is used: a = i++ yields the old value, a = ++i the new one. The ++i convention in for loops comes from C++, where i might be an iterator or another class type whose operator++(int) has to copy the object to return its previous state, a copy that's free to write and not always free to run, and which the compiler can only sometimes elide. That reasoning doesn't transfer to a plain int in C, where both forms are a single instruction. So the honest answer is that it's a style question in C, worth following your codebase's convention for consistency and not worth arguing about, while the underlying pre/post semantics genuinely matter the moment you use the result in an expression.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

for Loops, break & continue

The counted loop you'll write most often, plus the two escape hatches: break to leave early, continue to skip an iteration.

More for Loops, break & continue questions

Browse all 472 interview questions
What's the difference between for (int i = 0; ...; i++) and for (int i = 0; ...; ++i)? | EmbeddedPrep.io