for (int i=0;i<100;++i) ; for (int i=0;i<100;i++) ; 

Is there any difference how to write, because postfix ++ more difficult to implement?

  • whence the suspicion that postfix is ​​more difficult? - Grundy
  • Well, in the same place, a temporary copy is created - bulebyaka
  • @bulebyaka there will be inc eax anyway. - Vladimir Martyanov

3 answers 3

While you are working with built-in types of type int is no difference. Compilers are pretty smart.

With custom types there can be anything, I mean, a violation of semantics. Maybe someone will take it into his head to write files in the prefix, and erase them in the postfix :) If the semantics are observed, of course, the postfix is ​​more difficult to implement.

Therefore, it is recommended to teach yourself to write ++i - just to develop a habit :)

    It is better to use prefix operators in the calling code, unless you need the original value returned by the postfix version. The prefix form is semantically equivalent, it is introduced in much the same way, and often a little more efficiently, since it creates one less object. This is not a premature optimization, but the elimination of premature pessimization.

    Sutter, Alexandrescu. C ++ programming standards.

      The result of the third expression in for always ignored; only a side effect from its execution is important. This means that all code related only to the generation of its return value and the return thereof (if in this context a “return” makes sense at all) can be safely thrown out.

      For int i; for (int i=0;i<100;i++) ; int i; for (int i=0;i<100;i++) ; , by removing the dead code (writing a value that is not used further), the compiler can remove from i++ all nonessential code related to the return value of this expression, leaving only a side effect. And you get a code equivalent to ++i .

      The important thing is that the compiler here does not replace the postfix variant with the prefix one , but removes the extra code from the postfix one, which “by pure chance” for int turns out to be equivalent to its prefix “brother”. For other types, the equivalent code may easily be different.

      ... if your compiler is smart enough to do that at all. Most likely - enough. Here is an example in the compiler explorer (on the oldest version of the compiler that I found there), and it gives the same result. Switch the compiler, compare whether the code is the same.