Short answer:
There is never any difference between i++
and ++i
in terms of speed. A good compiler should not generate different code in the two cases.
Long answer:
What every other answer fails to mention is that the difference between ++i
versus i++
only makes sense within the expression it is found.
In the case of for(i=0; i<n; i++)
, the i++
is alone in its own expression: there is a sequence point before the i++
and there is one after it. Thus the only machine code generated is "increase i
by 1
" and it is well-defined how this is sequenced in relation to the rest of the program. So if you would change it to prefix ++
, it wouldn't matter in the slightest, you would still just get the machine code "increase i
by 1
".
The differences between ++i
and i++
only matters in expressions such as array[i++] = x;
versus array[++i] = x;
. Some may argue and say that the postfix will be slower in such operations because the register where i
resides have to be reloaded later. But then note that the compiler is free to order your instructions in any way it pleases, as long as it doesn't "break the behavior of the abstract machine" as the C standard calls it.
So while you may assume that array[i++] = x;
gets translated to machine code as:
i
in register A.i
in register A // inefficient because extra instruction here, we already did this once.i
.the compiler might as well produce the code more efficiently, such as:
i
in register A.i
.Just because you as a C programmer is trained to think that the postfix ++
happens at the end, the machine code doesn't have to be ordered in that way.
So there is no difference between prefix and postfix ++
in C. Now what you as a C programmer should be vary of, is people who inconsistently use prefix in some cases and postfix in other cases, without any rationale why. This suggests that they are uncertain about how C works or that they have incorrect knowledge of the language. This is always a bad sign, it does in turn suggest that they are making other questionable decisions in their program, based on superstition or "religious dogmas".
"Prefix ++
is always faster" is indeed one such false dogma that is common among would-be C programmers.