Why is arr[i] == i[arr] ?
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. 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; } |
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; } |
arr[0][1] = 2 1[arr[0]] = 2 1[0[arr]] = 2
Please note: 0[1][arr] generates an error.
Please Login to comment...