Logo

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

  1. Pointer Arithmetic
    The expression *(a + i) means “take the pointer a, offset it by i units (where each unit is the size of the type being pointed to), and then dereference.”

  2. 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).

  3. Practical Relevance

    • While 5[a] compiles and behaves identically to a[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.

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:

  1. Grokking Data Structures & Algorithms for Coding Interviews
    Gain a solid foundation in essential data structures and algorithms, complete with practical coding examples.

  2. 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.

CONTRIBUTOR
TechGrind