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

StackOverflow https://stackoverflow.com/questions/9080631

  •  21-04-2021
  •  | 
  •  

Question

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?

Was it helpful?

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.

OTHER TIPS

It's a stupid rule, IMHO. Its description is here

IllegalToken

Checks for illegal tokens.

Rational: Certain language features often lead to hard to maintain code or are non-obvious to novice developers. Other features may be discouraged in certain frameworks, such as not having native methods in EJB components.

By default, it forbids postfix increments, postfix decrements, and switches. You can safely disable the rule, or configure it differently.

My opinion is that your rule is a standard Java idiom, and that replacing i++ with ++i will have no other effect that making newbies ask themselves why the standard idiom isn't used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top