+ 1

# Why arr[1] and 1[arr] is same for array ? How to overload [] for class to work both these ways ?

Why arr[1] and 1[arr] is same for array ? How to overload [] for class to work both these ways ?

2 Answers

+ 2

In C++, an array name is a pointer to the first element of the array. So, arr[1] and 1[arr] are equivalent expressions because they both evaluate to *(arr + 1). This is because addition is commutative in C++, so arr + 1 and 1 + arr are equivalent expressions.

+ 1

the compiler converts the array operation into pointers before accessing the array elements, which means:
arr[i] == *(arr + i);
therefore arr[1] will evaluate to → *(arr+1), and 1[arr] will evaluate to → *(1 + arr) which is the same as *(arr + 1) and from elementary school math we know those are equal (addition is commutative).
NOTE: don’t use this syntax in real code. this only works for the built-in subscript operator.