#include <iostream> using namespace std; int main() { int arr[3] = { 10, 20, 30 }; cout << arr[-2] << endl; cout << -2[arr] << endl; return 0; } Output:
4196160 -30 Here arr[-2] is out of range and invalid, causing undefined behavior. But -2[arr] evaluates to -30. Why?
Isn't arr[-2] equivalent to -2[arr]?
-2[arr] is parsed as -(2[arr]). In C (and in C++, ignoring overloading), the definition of X[Y] is *(X+Y) (see more discussion of this in this question), which means that 2[arr] is equal to arr[2].
The compiler parses this expression
-2 like
unary_minus decimal_integer_literal That is definitions of integer literals do not include signs.
In turn the expression
2[arr] is parsed by the compiler as a postfix expression.
Postfix expressions have higher precedence than unary expressions. Thus this expression
-2[arr] is equivalent to
- ( 2[arr] ) So the unary minus is applied to the lvalue returned by the postfix expression 2[arr].
On the other hand if you wrote
int n = -2; and then
n[arr] then this expression would be equivalent to
arr[-2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With