Unusual (But Legitimate) Object References In C/C++
[C, C++]
When accessing an array in C/C++ (and, indeed, many C-based languages), you would access a particular element in an int array like this:
// Create and initialize an array of 5 numbers
int numbers[] = {1,2,3,4,5};
// Print the fifth
std::cout << numbers[4] << std::endl;
This will print, as we expect, 5.
This also works with strings:
// Create and initialize a char array
char hello[] = "Hello\t";
// Print the third letter
std::cout << hello[1] << std::endl;
This will print, as we expect, e.
What you might not know is that it is also 100% legit to do this:
std::cout << 1[hello] << std::endl;
This will print the same result.
These are also variations that will work:
std::cout << *( hello + 1 ) << std::endl;
std::cout << *( 1 + hello ) << std::endl;
Why does this work? Because arrays are ultimately pointers, and what we are doing is pointer arithmetic.
Happy hacking!