Stop Using i++ in Your Loops (2024)

Stop Using i++ in Your Loops (3)

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.

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:

int j = i;
i = i + 1;
return j;

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…

Stop Using i++ in Your Loops (2024)
Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 6431

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.