Can someone explain array[++index]
vs array[index++]
?
I am reading a data structure book and it seems like this notation does have a difference.
array[++index]
will first add 1 to the variable index
, and then gives you the value;
array[index++]
will give you the value at index
, and then increment index
.
array[++index] - increment to variable index in current statement itself. array[index++] - increment to variable index after executing current statement.
++index
will increment index by 1 before it's used. So, if index = 0, then arry[++index]
is the same as arry[1]
.
index++
will increment index by 1 after it's used. So, if index = 0, then arry[index++]
is the same as arry[0]
. After this, index will be 1.
The different behavior is not specific to arrays.
Both operators increment index
by one.
++index
returns index+1
while index++
return the original value of index
.
Therefore when used to access an array element, the two operators will give different indices.
let's say index is 0
array[++index]
give you element 1 and index is 1 after that
array[index++]
give you element 0 and index is 1 after that
The preincrement operator (++index
) first increments the variable and only then returns its value. So var = array[++index]
is equivalent to:
index += 1;
var = array[index];
The postincrement operator (index++
) first returns the value of the variable and only then increments its value. So var = array[index++]
is equivalent to:
var = array[index];
index += 1;