The difference in array increments in C

I am wondering what is the difference between array[i]++ and array[i++] , where array is int array[10] ?

+4
source share
5 answers
 int a[] = {1, 2, 3, 4, 5}; int i = 1; 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]++ increases the element in index i , it does not increase i . And a[i++] increments i , not the element in index i .

+8
source
  • array[i]++ increments the value of array[i] . An expression is evaluated to array[i] before it is expanded.
  • array[i++] increments the value of i . The expression evaluates to array[i] before i is incremented.

Illustration.

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

  • array[i]++ changes array[1] to 2, evaluates to 1 and leaves i equal to 1.
  • array[i++] does not change array , evaluates to 1 and changes i to 2.

The suffix operators that you use here evaluate to the value of the expression before it is incremented.

+11
source

array[i]++ means ( *(array+i) )++ . โ†’ Increases value.

array[i++] means *( array + (i++) ) . โ†’ Increases the index.

+4
source

here the array [i] ++ increases the value of the array of elements [i] but the array [i ++] increases the value i, which affects or changes the indication of the element of the array, that is, it indicates the element nxt of the array after the array [i].

+1
source

Here the array [i ++] increments the index number.
Conversely, the [i] ++ array increments the value of index i data.

Code snippet:

 #include <iostream> using namespace std; int main() { int array[] = {5, 2, 9, 7, 15}; int i = 0; array[i]++; printf("%d %d\n", i, array[i]); array[i]++; printf("%d %d\n", i, array[i]); array[i++]; printf("%d %d\n", i, array[i]); array[i++]; printf("%d %d\n", i, array[i]); return 0; } 
0
source

All Articles