What is the difference between array[i]++
and array[i++]
, where the array is an int array[10]
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With