Home > Blogs > 30 C++ Tips in 30 Days: Tip # 19 post-increment and pre-increment: which one is more efficient?

30 C++ Tips in 30 Days: Tip # 19 post-increment and pre-increment: which one is more efficient?

By  Dec 10, 2007

Topics: Programming, C/C++

Is there a difference between using the post-increment and pre-increment (++ operator) in a loop? If so, which of the two is better?

The following loop pre-increments the counter i:

for (int i=0; i<MAX; ++i)
{
//...
}

Seemingly, the above version is slightly more efficient than this version:

for (int i=0; i<MAX; i++)
{
//...

Note: regardless of the actual increment operator used (i.e., post or pre increment), the increment operation always takes place after the loop's body has executed, so i becomes 1 only after the first iteration. 

When the built-in ++ operator is used, the compiler is able in most cases to optimize the post-increment version thereof. Therefore, if you dissemble the optimized code of the two loops you will not find any difference between the two versions, which means that practically, there's no difference between post and pre incrementing. However, when the loop counter is a user-defined type (an iterator object, for example), there could be a difference between the post and pre increment overloaded operators so it's best to stick to the pre-increment as the default form.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.