Search code examples
javacheckstylejls

Why usage of prefix incrementation is considered better than postfix incrementation in standard for construction


I recently installed Checkstyle plugin for Eclipse and personally think that it is awesome. But one of the warnings it gives me is a bit obscure. The exact warning is "Using ++ is not allowed". It is about postfix ++ in some row like

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

Ok, I 'm aware that foreach is the better construction for iteration, but it can't be applied everywhere, sometimes old-school ++ is the only alternative.

When I change the row to

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

the warning disappears. I know the difference between i++ and ++i and to this point of my life I considered them interchangeable in standard for construction. But Checkstyle considers i++ harmful (or error prone).

Question: Why prefix incrementation is better than postfix incrementation in for constructions? Or... is it Checkstyle wrong about that?


Solution

  • Postfix incrementation makes sense only when used in an expression where you need the old value prior to the modification. In void contexts where that value is discarded (as is in your for loop), saving the old value makes no sense.

    In other words:

    // makes sense because you need the old value to subscript the array
    stack[top++] = x;
    // in a void context, the old value is discarded
    top++;
    

    In C++ in particular, both of these operators can be overloaded, and the implementation of the postfix one can be inefficient because of the requirement to return the old value - it usually involves copying the old object to comply with the original semantics of the postfix operator.

    With primitive types, any decent compiler will produce identical code for both of the cases, but the second one is better from the semantic standpoint of the language.