To i++ or to ++i…

Ξ April 25th, 2009 | → 0 Comments |
Programming |, , , |

The question is very simple. When writing a for loop, such as the following one

for( int i = 0; i < 10, /* increment i */ )

Between i++ or ++i, which increment operator would you use? Why?

If you choose the answer “It’s the same! Both increment i.“, or if your answer was “I have always used i++, because /* some place ulterior reason here, like ‘I’m programming in c++ and not in ++c’ */“, then your might thing improving your c++ knowledge a little bit. :-)

I just learned it myself, so I’ll share. In fact, it’s so simple it makes me wonder how many of these small details are missed every time my C++ source code lines are incremented. The best increment operator to be used in the pre-increment.

Why? Because it avoids the creation of a temporary variable. Post-increment (i++) has to create a temporary variable to store the return result (that you won’t be using), while incrementing this as expected. Pre-increment simply increments the value of this and returns.

So, systematically using ++i, instead of i++, should improve your runtime performance - even if so slightly.

 

On the nightstand...


    The Art of Agile Development


    Beautiful Architecture


    Modern C++ Design


    Large Scale C++ Software Design

Personal

Friends


Interesting


Shared Readings