C(和C ++)循环中的代码样式:后缀和前缀增量 [英] Code style in C (and C++) loops: postfix and prefix increments

查看:87
本文介绍了C(和C ++)循环中的代码样式:后缀和前缀增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些天,我经常看到这种情况:

These days I see this very often:

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

而不是-就像20年前的时尚(?)一样-

Rather than - as was very much the fashion (?) 20 years ago - this:

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

是有这种变化的原因还是仅仅是时尚?

Is there a reason for this change or is it just fashion?

(这里有一个关于Java的类似问题,但我认为答案并不重要)

(There is a similar question about Java here but I don't think the answers get to the heart of the matter)

推荐答案

主要是时尚,但又兼具一致性和误解.

It's mostly fashion, but also a combination of consistency and misunderstanding.

当迭代器出现时,越来越多的人开始意识到 ++ it 可能比 it ++ 更便宜,因为它的指针要复杂得多迭代器 it ,他们开始习惯在每个地方进行预增量,以将它们认为不必要的副本保存为后增量的语义(原始值必须临时存储,以用于增量发生后返回).然后他们也会对整数也这样做,因为为什么不这样做?

When iterators came along, and more and more people started realising that ++it could be cheaper than it++, for some more-complex-than-a-pointer iterator it, they started getting into the habit of pre-incrementing everywhere, to save what they perceived to be unnecessary copies in the semantics of a post-increment (the original value would have to be stored temporarily for returning after the increment occurs). They'd then do that for integers too, because why not?

实际上,没有什么可保存的.您的编译器完全有能力发现这里从未使用过的评估结果,因此在此上下文中 ++itit++ 具有完全相同的语义(除非有一些非运算符定义中的惯用副作用).对于简单的整数 i 尤其如此.

In reality, there's nothing to save. Your compiler is perfectly capable of spotting that the evaluated result is never used here, so ++it and it++ in this context have exactly identical semantics (unless there is some non-idiomatic side effect in the definition of the operator). This is particularly the case for a simple integer i.

它当然不会造成伤害,并且确实消除了您错过了确实会导致不必要的复制的某些怪异角度的风险.这是一个好习惯.只是它并不是出于必要而产生的.

It doesn't hurt, of course, and it does eliminate the risk that you've missed some weird angle that does result in an unnecessary copy. It's a good practice. It's just that it hasn't come about out of necessity.

这篇关于C(和C ++)循环中的代码样式:后缀和前缀增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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