projectb14ck

Random thoughts of a happy programmer.

Neat Thing I Learned Today – Part 1

In C, you can index arrays with either the array subscript inside of the typical square brackets:

arr[0]
or, with the less common (and somewhat mistifying):

0[arr]
Now, I’ve been using C for quite a while, but never realized that you could do this. It is definitely awesome, and could be really useful in some obfuscated programs. Now, just to make sure that this actually works, feel free to test it out. I wrote a really small sample program that runs a test (if it doesn’t work, please leave a comment with your compiler as I’d be interested to know if it doesn’t work on all platforms. Anyhow, feel free to use my source if you want.

The really interesting thing about this, is why it works. On the Stack Overflow discussion page for Strangest language feature, the user Michel explains why it works.

that’s because a[10] means *(a+10) … and 10[a] means *(10+a) :)

Pretty awesome. Anyhow, hope you learned something new, I sure did! Thanks Stack Overflow :)

  • Digg This Post
  • Tweet This Post
  • Stumble This Post
  • Submit This Post To Delicious
  • Submit This Post To Reddit
  • Submit This Post To Mixx

Author: b14ck

Randall is the lead developer for a mid-size communications company, and also works on his own telephony services company with a friend. On his free time he enjoys going out with his fiancée, and programming. He also works on several large open source projects, and enjoys reading technical books.

Leave a Reply

© 2008-2009 projectb14ck
Powered by Wordpress and made by Guerrilla