Hack of the day: Access to arrays in c/c++
December 26, 2010
If you want to access an array in c/c++ it’s very common to use the following code:
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << a[10] << std::endl; // 10
But it’s also possible to achieve the exact same behaviour using the following lines:
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << 10[a] << std::endl; // 10
This works because a[10] means the same as *(a+10) and 10[a] means *(10+a) which is the same.
This behaviour can be used to access strings like this:
char c = 4["hi over there"]; //c == "v"
I had never seen array access like 10[a] before in my life, and was surprised to see it does work as you’ve written.