2

Looking at some weird obfuscation contest code today I realized that array indexing is symmetric, in other words, x[n] is the same as n[x]. For example, consider the code below:

#include <iostream>

int main()
{
    int x[] = {0, 1, 2, 3, 4};
    std::cout << x[3] << ' ' << 3[x]; // both display 3
}

Live on Coliru

Is this indeed standard compliant, and if yes, is there any good reason why? And a bonus if you can provide a standard reference/quote.

PS: the code compiles fine with both gcc and clang

vsoftco
  • 55,410
  • 12
  • 139
  • 252

1 Answers1

2

The reason is that in C (and C++) both expressions are equal to *(x + 3) == *(3 + x).

Innot Kauker
  • 1,333
  • 1
  • 18
  • 30