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 of array[i]. The expression evaluates to array[i] before it has been incremented.
  • array[i++] increments the value of i. The expression evaluates to array[i], before i has been incremented.

An illustration.

Suppose that array contains three integers, 0, 1, 2, and that i is equal to 1.

  • array[i]++ changes array[1] to 2, evaluates to 1 and leaves i equal to 1.
  • array[i++] does not modify array, evaluates to 1 and changes i 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.

Tags:

C

Arrays