NOGDUS Archives - Obscure C++ Syntax
Originally written for NOGDUS in 2010. Edited and formatted for ToV in 2014.
OK, today I just discovered an apparently undocumented (as far as I can tell - hours of googling has returned nothing) feature of the C++ language.
You likely already know that you can create arrays of data types using the brackets:
int myarray[100];
And that the size is optional if you initialize inline:
int myarray[] = {1,2,3,4,5,6};
And that you access the elements of the array like this:
int index = 4; int value = myarray[index]; // value = 5 using the array init above
But here is what I just learned.
You can use the array name as the index and the index as the variable! :o
int index = 3; int value = index[myarray]; // value = 4 using the array init above
This also works:
int value = 3[myarray];
Woah.. coolness! This lets you do some interesting things. Here is a fun little program. See if you can figure out what it does BEFORE you try it out!
#include <iostream> using namespace std; int main(int argc, char* argv[]) { char god[] = " !ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int am_a[] = { 9, 6, 13, 13, 16, 0, 24, 16, 19, 13, 5, 1 }; for (unsigned int i = 0; i < (sizeof(am_a) / sizeof(int)); i++) { cout << i[am_a][god]; } cout << endl; return(0); }
Pretty slick stuff. I love C++. 8)














