vsoftco vsoftco - 7 months ago 42
C++ Question

Why is array indexing symmetric in index and name

Looking at some weird obfuscation contest code today I realized that array indexing is symmetric, in other words,

is the same as
. 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


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