Open In App

Why is arr[i] == i[arr] ?

Improve
Improve
Like Article
Like
Save
Share
Report

The subscript operator is defined as follows according to the C documentation:

x[y] == *((x) + (y))

So, if we have declared an array as int arr[5] = {1, 2, 3, 4, 5};

Then, arr[2] = *(arr + 2)

Here the name of the array decays into the pointer to the first element of the array.

arr is considered the pointer to the first element of this array. When we do arr+i, this new pointer will point to the next element in the array, based on the size of the datatype.

For example: In this given arr array, each element is an integer so it takes 4bytes in the memory. So when we write (arr+1) it skips 4bytes and points to the 2nd element of the array. Similarly for (arr+2), it will skip 2*4bytes i.e. 8 bytes, and point to the third element of the array.

We must understand these basics:

        arr[i] = *(arr + i)

        i[arr] = *(i + arr),

The above is equivalent to:

*(2 + arr)

which according to the definition of the subscript operator is equal to

2[arr]

Let’s look at the implementation of the above:

C




#include <stdio.h>
 
int main()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
    printf("arr[2] = %d\n", arr[2]);
    printf("2[arr] = %d\n", 2 [arr]);
    return 0;
}


Output

arr[2] = 3
2[arr] = 3

We can even extend this concept to multidimensional arrays. 

If we look at operator precedence and Associativity in C, we can clearly see that the subscript operator associates left to right. So if we have a 2 dimensional array int arr[2][2] = {1, 2, 3, 4};

Then, arr[0][1] = *(arr + 0)[1] = *(*(arr + 0) + 1)

Now we can use the commutative of addition to arrive at multiple forms of the above expression, like:

1[arr[0]], or  1[0[arr]]

Let’s look at the implementation with an example:

C




#include <stdio.h>
 
int main()
{
    int arr[2][2] = { 1, 2, 3, 4 };
    printf("arr[0][1] = %d\n", arr[0][1]);
    printf("1[arr[0]] = %d\n", 1 [arr[0]]);
    printf("1[0[arr]] = %d\n", 1 [0 [arr]]);
    return 0;
}


Output

arr[0][1] = 2
1[arr[0]] = 2
1[0[arr]] = 2

Please note: 0[1][arr] generates an error.



Last Updated : 05 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads