Skip to content
Related Articles

Related Articles

Why is a[i] == i[a] in C/C++ arrays?
  • Difficulty Level : Medium
  • Last Updated : 01 Jul, 2017

The definition of [] subscript operator operator in C, according to (C99, 6.5.2.1p2), is that

 E1[E2] is identical to (*((E1)+(E2)))

Compilers use pointer arithmetic internally to access array elements. And because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Therefore, a[b] is defined as :

a[b] == *(a + b)

So will evaluate to

a[8] == *(a + 8)

Here, a is a pointer to the first element of the array and a[8] is the value of an elements which is 8 elements further from a, which is the same as *(a + 8) and 8[a] will evaluate to following which means both are same.



8[a] == *(8 + a)

So by addition commutative property, a[8] == 8[a]

Sample program showing above results :




// C program to illustrate
// a[i] == i[a] in arrays 
#include <stdio.h>
int main()
{
    int a[] = {1, 2, 3, 4, 5, 6, 7};
    printf("a[5] is %d\n", a[5]);
    printf("5[a] is %d\n", 5[a]);
    return 0;
}


Output:

a[5] is 6
5[a] is 6

This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :