Increment operator inside array
The ++i
increments i
before evaluating it.
The i++
inrements i
after evaluating it.
If i=1
then array[++i]
sets i=2
and then fetches array[2]
.
If i=1
then array[i++]
fetches array[1]
then sets i=2
.
The post- and pre- operations happen after or before the expression they are involved in is evaluation.
I generally discourage the use of post and pre increment operators in expressions. They can lead to confusion at best and bugs at worst.
Consider what x = array[++i] + array[i--] ;
should be. See how easy it is to confuse the programmer ( or the poor devil who has to fix your code ? :-) ).
Post and pre increment and decrement operations can also produce problems in macros, as you end up with the potential for an operation to be duplicated multiple times, especially with macros.
It is simpler and produces easier to maintain code to avoid post and pre increments in expressions, IMO.
Please explain these operations.
array[++i];
- first incrementsi
, then gives you element at the incremented indexequivalent to:
++i; // or i++ array[i];
array[i++];
- also first incrementsi
, but postfixoperator++
returnsi
's value before the incrementationequivalent to:
array[i]; ++i; // or i++
They increment a variable inside array.
No, they don't. You could say they increment i
within the call to array subscript operator.
So, you know i++
and ++i
increment i
with 1. Also, this instruction returns i
, so you can put this somewhere in your code where you need the value of i
.
The difference between the 2 is that i++
is post increment, and ++i
is pre increment. What does this mean?
Well, let's say i
is 6. When you do:
array[i++]
array[i]
You will actually be doing:
array[6]
array[7]
Because you use post increment: first return value, then increment i
.
If you do:
array[++i]
array[i]
You'll basically be doing:
array[7]
array[7]
Because you use pre increment: first increment i
, then return its value.
Now try to find what your code does ;-)
Hope this helps.
array[++i]; - increments the value of i and then uses the incremented value as an index into array
array[i++]; -indexes into the array and then increments the value of i