Why isn't arr[-2] equivalent to -2[arr]?

msc picture msc · Jun 5, 2017 · Viewed 8.7k times · Source
#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]?

Answer

Chris Jefferson picture Chris Jefferson · Jun 5, 2017

-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].