Stop Using i++ in Your Loops

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

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

Introduction

If you’ve written a for-loop before, then you have almost definitely used i++ 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 i++ is that i is one higher than it was before — which is what we want. But, there are many ways to accomplish this, such as ++i, i++, and even i = i + 1.

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


Post-Increment (i++)

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

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

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

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 i, and it is simply discarded.


Pre-Increment (++i)

The ++i 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 i:

Notably, here, we do not have to save the old value of i — 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 i in that context.


Caveats

After seeing the difference between post-increment and pre-increment, one might notice that, since the cached value of i 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

Software Engineering / Machine Learning

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