Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array increment types in C - array[i]++ vs array[i++]

Tags:

arrays

c

What is the difference between array[i]++ and array[i++], where the array is an int array[10]?

like image 374
samprat Avatar asked Sep 29 '11 09:09

samprat


People also ask

Can you increment an array in C?

You can not increment an array variable. You can do something like: int *p = array; p += whatever; just make sure that you don't deference p when it is pointing to any element beyond the last element of the array.

What is difference between ++ i and i ++?

The only difference is the order of operations between the increment of the variable and the value the operator returns. So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.

What is array increment?

To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.

What is the meaning of ARR i ]++?

In this example i = 3 so,arr[3]= 40 and then it increases the value 40 to 41.So arr[i]++ increments the value of this particular index and a[i++] first increment the index and then gives the values of this index.


2 Answers

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.

like image 92
taskinoor Avatar answered Oct 13 '22 15:10

taskinoor


  • 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.

like image 37
David Heffernan Avatar answered Oct 13 '22 16:10

David Heffernan