The underlying problem is with operator precedence. In C++ the []
, ie the Subscript operator hold more precedence (somewhat akin to preferance) than the -
unary_minus operator.
So when one writes,
arr[-2]
The compiler first executes arr[]
then -
, but the unary_minus is enclosed within the bounds of the [-2]
so the expression is decomposed together.
In the,
-2[arr]
The same thing happens but, the compiler executes 2[]
first the n the -
operator so it ends up being
-(2[arr])
not (-2)[arr]
Your understanding of the concept that,
arr[i]
i[arr]
and *(i+arr)
are all the same is correct. They are all equivalent expressions.
If you want to write in that way, write it as (-2)[arr]
. You will get the same value for sure.
Check this out for future referance :http://en.cppreference.com/w/cpp/language/operator_precedence