Code style in C (and C++) loops: postfix and prefix increments

我是研究僧i 提交于 2021-02-11 15:42:34

问题


These days I see this very often:

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

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?

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


回答1:


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

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?

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.




回答2:


C and C++

Post-increment involves a temporary that can be avoided by using pre-increment (Post-increment and Pre-increment concept?).

C++

If only integers are involved, the issue is not that critical and the compiler can probably optimize both versions to do essentially the same. However, in C++ basically any object of class type can have a ++ (both post- and pre-) and that can be overloaded to do basically anything. Post-incrementing a big object has a cost and depending on how to operator is implemented the compiler might not be able to optimize both post- and pre-increment to do essentially the same thing. To be on the save side it is prefered to use ++i.

20 years ago

Actually the only thing that changed with respect to this issue is that compiler optimizations got much better over time. I didn't check any old compiler, but I would say that 20 years ago missing compiler optimizations were a much stronger reason to use ++i instead of i++. Maybe what you observed is just style of code getting better.



来源:https://stackoverflow.com/questions/61455995/code-style-in-c-and-c-loops-postfix-and-prefix-increments

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