为什么使用前缀增量被认为比构造标准中的后缀增量更好 [英] Why usage of prefix incrementation is considered better than postfix incrementation in standard for construction

查看:99
本文介绍了为什么使用前缀增量被认为比构造标准中的后缀增量更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近为 Checkstyle 插件。 org /rel =noreferrer> Eclipse 并且个人认为它很棒。但它给我的一个警告有点模糊。确切的警告是不允许使用 ++ 。它是关于某些行的后缀 ++ ,如

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++)

好的,我知道 foreach 是迭代的更好构造,但它无法在任何地方应用,有时候老式的 ++ 是唯一的选择。

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.

当我将行更改为

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

警告消失。我知道 i ++ ++ i 之间的区别,到了我生命的这一点,我认为它们可以在标准中互换code>用于构造。但是Checkstyle认为 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).

问题:为什么要加前缀对于构造,增量优于中的后缀增量?或者...... Checkstyle错了吗?

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

推荐答案

Postfix增量只有在你需要的表达式中使用才有意义修改前的旧值。在无效上下文中,该值被丢弃(就像中的循环一样),保存旧值是没有意义的。

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.

换句话说:

// 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++;

特别是在C ++中,这两个运算符都可以重载,后缀的实现可以因为需要返回旧值而效率低下 - 它通常涉及复制旧对象以符合后缀运算符的原始语义。

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.

这篇关于为什么使用前缀增量被认为比构造标准中的后缀增量更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆