The binary expression:
x[y]
is defined to be equal to:
*(x+y)
(in the absence of operator []
overloads).
3+a
is the same as a+3
so 3[a]
is the same as a[3]
.
In the context of 3+a
, the name of array a
decays to a pointer to its first element, so we are trying to add a pointer and an integer using the builtin addition operator. The latest draft of C++14 says in section 5.7 [expr.add] para 4:
When an expression that has integral type is added to or subtracted from a pointer, the result has the type
of the pointer operand. If the pointer operand points to an element of an array, and the array is
large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if
the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P))
and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array
object, provided they exist
This is very close to the text of the C++14 standard, but this behaviour has been stable since C89 (and actually since BCPL in the '70s).
Having said that, if you find code like this hunt down the author and beat him over the head with a clue-bat. It is very easy to write C++ that nobody (including yourself after a week) can read - and that is no use to anyone.