Array indexing or index array-ing

In the code snippet below, line 7 is standard ... but why on earth does line 8 work?

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
   int a[4] = { 15, 25, -12, 42 };
   cout << a[2] << '\n';
   cout << 2[a] << '\n';
}
Because x[y] is equivalent to *(x + y).

a[2] = *(a + 2) = *(2 + a) = 2[a]
Last edited on
That's great, @Peter87! (And thanks for re-editing.)

With your pointer arithmetic I can now see the logic - but I don't think I would dare use that form in my own code.

Thanks.
Last edited on
Topic archived. No new replies allowed.