C++ - Obscure Syntax

(1/2) > >>

Richard Marks:
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:
Code:

int myarray[100];

And that the size is optional if you initialize inline:
Code:

int myarray[] = {1,2,3,4,5,6};

And that you access the elements of the array like this:
Code:

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

Code:

int index = 3;
int value = index[myarray]; // value = 4 using the array init above


This also works:
Code:

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!
Code:

#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)

kingthomas:
Awesome, I never knew about 3[myArray]. Good stuff to know.

xhunter:
Amazing and rare stuff ! hope to find something like this in Ruby lol !

Richard Marks:
Quote from: xhunter on March 02, 2010, 04:36:09 AM

Amazing and rare stuff ! hope to find something like this in Ruby lol !


I can't fathom why you would want to find something like that in Ruby ::)
But here is my favorite Ruby reference site. 8)

RedSlash:
This topic should be "C++ obscure syntax" rather than "c++ advanced arrays". Great find!

Navigation

[0] Message Index

[#] Next page