I am reading through the section about pointers and arrays from "The c++ programming language", and I came across something that stumps me.

For every built-in array a and integer j within the range of a, we have:

a[j] == *(&a[0]+j) == *(a+j) == *(j+a) == j[a]

I understand why *(&a[0]+j) means the same as a[j], because &a[0] points to the first element of a and then it's incremented by j.

I also get that *(a+j) and *(j+a) are equal to a[j], a gets implicitly converted from an array to a pointer to the first element of a, and then incremented by j and dereferenced.

But why is a[j] == j[a]? What am I missing?

1 Answers

eerorika On Best Solutions

Because the subscript operator is commutative. It is simply specified to be so by the language.

You can see the symmetry from the equivalence with the pointer arithmetic expressions, where the addition operator is also commutative:

a[j] == ∗(a+j)
j[a] == ∗(j+a)
∗(a+j) == ∗(j+a)

The language standard (draft) says:


... The expression E1[E2] is identical (by definition) to *((E1)+(E2)) ...

[Note: Despite its asymmetric appearance, subscripting is a commutative operation except for sequencing.