Just a little insight into arrays in C/C++:
An arrray is in essence just "syntactic sugar" for pointer-arithmatic.
If you have for example defined an array of 4 integers,
C++:
int a[4] = { 42, 43, 44, 45 };
the symbol 'a' is internally just a pointer to the first element.
Using the index-operator (
[]) just adds the index to the pointer. This is also the reasoning why C/C++ starts countig from 0, as it's much more efficient this way.
So defining this...
C++:
int a[4] = { 42, 43, 44, 45 };
int i = 1;
... and accessing the 2nd Element (Index 1, you know) by...
... is just the same as...
(the ampersand is just here to emphazise that 'a' is actually a pointer to int)
Incrementing a pointer-to-a-type by an integer 'N' just increments the pointer value by 'N' times the size of the type.
With this knowledge you can see why this COMPLETELY INSANE programming is still working:
C++:
#include <iostream>
int main (int argc, char** argv)
{
int a[4] = {42,43,44,45};
int i = 1;
int x = a[i];
int y = i[a]; // WHAAAAT?! But it's the same as above!
std::cout << "x:" << x << ", y:" << y;
return 0;
}
The above does print out the (un)expected result:
int main (int argc, char** argv) { int a[4] = {42,43,44,45}; int i = 1; int x = a[i]; int y = i[a]; // WHAAAAT?! But it's the same as above! std::cout << "x:" << x << ", y:" << y; }
godbolt.org
..just to keep the confusion level up
