简体   繁体   中英

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

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM