开发者

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

开发者 https://www.devze.com 2023-04-09 11:43 出处:网络
What is the difference between array[i]++ and array开发者_Python百科[i++], where the array is an int array[10]?int a[] = {1, 2, 3, 4, 5};

What is the difference between array[i]++ and array开发者_Python百科[i++], where the array is an int array[10]?


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.


Here the Array[i]++ increments the value of the element array[i], but array[i++] increments the i value which effects or changes the indication of the array element (i.e. it indicates the next element of an array after array[i]).


Let's say we have this example, array[i++] = x[m++]. This means that first set array[i] = x[m] then increase the indexes like i + 1, m + 1.


I believe it's also worth mentioning that array[++i] increments before the evaluation, and as has been mentioned earlier array[i++] increments the i (or index) value after the evaluation.

Example:

array[++i]; = i++; array[i];

array[i++]; = array[i]; i++;


#include<iostream>
using namespace std;
int main()
{
    int arr[]={1,2,37,40,5,7};
    int i = 3;
    arr[i]++;
    cout<<i<<" "<<arr[i]<<endl;
    arr[i++];
    cout<<i<<" "<<arr[i]<<endl;
    return 0;
}

output:

3 41
4 5

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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消