With arrays in C, why is it the case that a[5] == 5[a]?
In C, array subscript notation a[i]
is actually defined as syntactic sugar for pointer arithmetic:
a[i] ≡ *(a + i)
Similarly, by commutative property of addition for pointers:
i[a] ≡ *(i + a) ≡ *(a + i)
Hence, a[i]
and i[a]
refer to the same underlying pointer arithmetic. Both evaluate to the same memory location and yield identical results.
In More Detail
-
Pointer Arithmetic
The expression*(a + i)
means “take the pointera
, offset it byi
units (where each unit is the size of the type being pointed to), and then dereference.” -
Syntactic Sugar
In the C standard,a[i]
is defined as*(a + i)
. But since addition is commutative,*(a + i)
is the same as*(i + a)
. Therefore,i[a]
is another (uncommon) way of writing*(a + i)
. -
Practical Relevance
- While
5[a]
compiles and behaves identically toa[5]
, it’s rarely used in real code, as it’s much less readable. - It’s a quirk of how C language definitions treat array subscript notation in terms of pointer arithmetic.
- While
Further Reading & Practice
If you want to strengthen your understanding of pointers, arrays, and other data structures in C and beyond, two highly recommended courses from DesignGurus.io are:
-
Grokking Data Structures & Algorithms for Coding Interviews
Gain a solid foundation in essential data structures and algorithms, complete with practical coding examples. -
Grokking the Coding Interview: Patterns for Coding Questions
Learn to quickly identify and apply common problem-solving patterns, giving you a significant advantage in technical interviews.
Both courses cover fundamental programming concepts that underscore why oddities—like 5[a]
—work the way they do in C, and how these concepts connect to larger topics like pointers, memory management, and efficient coding patterns.