This is funny and simple. -array[2]
is the same as -*(array + 2)
, which is the same as -*(2 + array)
which is the same as -2[array]
, which is -30.
There is already a duplicate for general case of using square brackets with arrays (With arrays, why is it the case that a[5] == 5[a]?), but the quirk here is the unary -
operator in front.
It might seem intuitive to assume that the actual array index would be -2
, like array[-2]
.
But this is not happening due to operator precedence rules:
operator []
has higher precedence than unary -
, and as such is applied first.
I've shown the tranformation with 'conventional' array subscription to make this more intuitive
- as we do not negate the array before subscripting it, we do not negate 2 the same way.