Array increment types in C - array[i]++ vs array[i++]
int a[] = {1, 2, 3, 4, 5};
int i = 1; // Second index number of the array a[]
a[i]++;
printf("%d %d\n", i, a[i]);
a[i++];
printf("%d %d\n", i, a[i]);
Output
1 3
2 3
a[i]++
increments the element at index i
, it doesn't increment i
. And a[i++]
increments i
, not the element at index i
.
array[i]++
increments the value ofarray[i]
. The expression evaluates toarray[i]
before it has been incremented.array[i++]
increments the value ofi
. The expression evaluates toarray[i]
, beforei
has been incremented.
An illustration.
Suppose that array
contains three integers, 0, 1, 2, and that i
is equal to 1.
array[i]++
changesarray[1]
to 2, evaluates to 1 and leavesi
equal to 1.array[i++]
does not modifyarray
, evaluates to 1 and changesi
to 2.
A suffix operators, which you are using here, evaluates to the value of the expression before it is incremented.
array[i]++
means ( *(array+i) )++
. --> Increments the Value.
array[i++]
means *( array + (i++) )
. --> Increments the Index.