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

怎甘沉沦 提交于 2019-12-18 20:02:09

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9080567/why-usage-of-prefix-incrementation-is-considered-better-than-postfix-incrementat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!