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:

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[])
    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;

Pretty slick stuff. I love C++. 8)

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

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)

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


[0] Message Index

[#] Next page