02 December 2011

Coding tip: i++ vs. ++i

Using the index i is very popular in coding, and as every developer knows, there are two ways to increment it:
  1. i++: increments i, but returns the pre-increment value.
  2. ++i: increments i, and returns the post-increment value.
Now, suppose you have a generic for loop, what would you use to increment i?

for(int i = 0; i < N; i++)
{
    doSomething();
}

OR

for(int i = 0; i < N; ++i)
{
    doSomething();
}

The school way says using i++, but let's think about it...

Compiling "i++" will be something like that (assembly pseudo-code):
      tmp = i
      i = i + 1
      return tmp

However, compiling "++i" will look like this:
      i = i + 1
      return i

So, using ++i will save one assembly assignment command and therefore, it's better to use ++i to increment the index in cases you don't use the pre-increment value.

Note1: I'm pretty sure that most of the compilers will optimize using i++ and convert it to ++i automatically, but coding the right way shows understanding which is valuable.

Note2: While I tried to write i < N w/o the spaces, blogger popped-up a warning says that my text has no ending delimiter, although I'm under "Compose" tab and not "HTML" tab... nice BUG :)



8 comments:

Anonymous said...

Wonderful blog! Do you have any tips for aspiring writers? I'm planning to start my own blog soon but I'm a little lost on everything. Would you suggest starting with a free platform like Wordpress or go for a paid option? There are so many choices out there that I'm completely overwhelmed .. Any suggestions? Many thanks!

Anonymous said...

Good post. I was examining consistently this kind of web site using this program . pleased! Very useful details especially the staying area I preserve this kind of data a great deal. I used to be seeking this particular data for a long period. Thank you and best regarding fortune.

Anonymous said...

I signed up to your rss feed! Will you post much more about this theme? Precisely what I required to get. Really clear and valuable post. Im certainly a violator of many of these guidelines.

Anonymous said...

Thanks for your information!

Unknown said...

Thanks to you for reading it. I'll be posting such tips whenever it comes to my mind :)

Anonymous said...

Give you confidante inasmuch as your post. It helped me alot in completing my work. [url=http://onlinepaydayloanz.com]Payday Loans[/url]

Anonymous said...

test

Anonymous said...

Hello. And Bye.