- i++: increments i, but returns the pre-increment value.
- ++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 :)
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 :)