Stop Using i++ in Your Loops

Why ++i is often better than i++ (pre-increment vs. post-increment)

Devin Soni 🤔
Nov 6, 2019 · 2 min read
Photo by Safar Safarov on Unsplash

Introduction

If you’ve written a for-loop before, then you have almost definitely used before to increment your loop variable.

However, have you ever thought about why you choose to do it like that?

Clearly, the end result of is that is one higher than it was before — which is what we want. But, there are many ways to accomplish this, such as , , and even .

In this article, I will cover two methods of adding 1, , and , and explain why may be better than in most situations.


Post-Increment (i++)

The method, or post-increment, is the most common way.

In psuedocode, the post-increment operator looks roughly as follows for a variable :

Since the post-increment operator has to return the original value of , and not the incremented value , it has to store the old version of .

This means that it typically needlessly uses additional memory to store that value, since, in most cases, we do not actually use the old version of , and it is simply discarded.


Pre-Increment (++i)

The method, or pre-increment, is much less common and is typically used by older programmers in languages such as C and C++.

In psuedocode, the pre-increment operator looks roughly like this for a variable :

Notably, here, we do not have to save the old value of — we can simply add to it and return. This aligns much better with the typical use-case in a for-loop, since we rarely need the old value of in that context.


Caveats

After seeing the difference between post-increment and pre-increment, one might notice that, since the cached value of is never used in post-increment, the compiler will just optimize that line away, making the two operators equivalent.

This is most likely true for primitive types, such as an integer.

However, for more complex types, such as user-defined types or iterators with the operation overloaded, the compiler may not be able to safely optimize the caching operation.

So, it seems that in most cases, the pre-increment operator is better than, or equal to, the post-increment operator, as long as you do not need the previous value of whatever you are incrementing.

Better Programming

Advice for programmers.

Devin Soni 🤔

Written by

Don’t forget to clap 👏 and follow!

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade