2

To reiterate: Why does array_name[index] == index[array_name] in C++?

I am struggling to find anything online that explains why you can reference an element like this in C++. I have a java background and do not understand the nuances of C++ that well.

Here is an example illustrating the question:

#include <iostream>

using namespace std;

int main()
{
    int data[3] = {1, 2, 3};
    if (data[2] == 2[data])
    {
        cout << "equal" << endl;
        cout << data[2] << ", " << 2[data] << endl;
    }
    else
    {
        cout << "not equal" << endl;
    }
}

Output:

equal
3, 3
Garrett
  • 319
  • 1
  • 13
  • 2
    This is a very quirky historical artifact of C and nobody would ever do this in production code. – tadman May 10 '20 at 21:49
  • 5
    `array_name[index]` is syntactical sugar for `*(array_name + index)` and of course `*(array_name + index) == *(index + array_name)` – Thomas Sablik May 10 '20 at 21:50
  • 1
    The "trick" (or syntactical historical artifact oddity) doesn't work with `operator[]` overload. – Eljay May 10 '20 at 22:17

0 Answers0