Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 614
Kiril Kirilov Avatar asked Jan 31 '12 13:01

Kiril Kirilov


2 Answers

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.

like image 79
JB Nizet Avatar answered Sep 19 '22 08:09

JB Nizet


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.

like image 23
Blagovest Buyukliev Avatar answered Sep 18 '22 08:09

Blagovest Buyukliev