Possible Duplicate:
What is more efficient i++ or ++i?
No difference between these:
i++;
++i;
But when using them like this:
anArray[ i++ ] = 0;
anArray[ ++i ] = 0;
Is there a difference?
TO BE EDITED: Thanks
Possible Duplicate:
What is more efficient i++ or ++i?
No difference between these:
i++;
++i;
But when using them like this:
anArray[ i++ ] = 0;
anArray[ ++i ] = 0;
Is there a difference?
TO BE EDITED: Thanks
Very much so.
i++ -> use i first and then increment it's value
++i -> increment i first and then use i's new value
i++ uses the value and then increments it.
++i increments the value and then uses it.
Suppose i=3
.
anArray[ i++ ] = 0;
Sets element at array index 3 to 0.
anArray[ ++i ] = 0;
Sets element at array index 4 to 0.
It is all about order of operations:
E.g.
int i = 1;
int a = i++;
Is equivalent to:
int i = 1;
int a = i;
i++;
While the opposite is:
int i = 1;
i++;
int a = i;
Do note that statements like these are undefined in C++.
int i = 0;
i = i++;
Yes! Big difference!
i++
increments i
after the line of code is executed expression is evaluated. ++i
increments it before. For example:
int i = 2;
printf("%i\n", i++); //prints "2"
printf("%i\n", i); //prints "3"
Compare with:
int i = 2;
printf("%i\n", ++i); //prints "3"
printf("%i\n", i); //prints "3"
And I've heard that ++i
is ever so slightly faster. Here is more on that.
Hope this helps!
UPDATE 2: Killed the last update, since the code technically had undefined behaviour. Moral of that story: Don't use foo(i, ++i)
, foo(++i, ++i)
, foo(i++, i)
, etc. Or even array[i] = ++i
. You don't know what order the expressions get evaluated in!
If you use them as statements by themselves there is no difference in the output. But if you use them as an expression then there is a subtle difference.
In the case of anArray[ i++ ] = 0;
i
is incremented after the assignment is done. Whereas in the case of anArray[ ++i ] = 0;
i
is incremented before the assignment is done.
For example of i = 0
, then anArray[ i++ ] = 0;
will set anArray[ 0 ]
to 0
and i
will be incremented to 1
. But if you use anArray[ ++i ] = 0;
then anArray[ 1 ]
is set to 0
since i
is already incremented.