Category Archives: coding trivia

Interesting C code

This is interesting only for C programmers, and probably not useful even to them.
But you’re still reading, so I guess you’re really jobless. So here it is:
Anyone familiar with pointers in C knows the output of this code:

int arr[3] = {5,6,7};

(OUTPUT : 7)

But did you know that even this code works :

int arr[3] = {5,6,7};

(OUTPUT : 7)

Amazing, huh?

(Nah, not really… I just write these articles to show people that they’re geeks! But do read on…)

Well, here’s how it works:

You probably know that arr[2] is equivalent to *(arr + 2)

Actually, arr[2] converts internally to *(arr + 2) before evaluation

So, if

arr[2] => *(arr + 2)

Isn’t it quite reasonable to  expect that

2[arr] => *(2 + arr)

Well, reasonable or not, thats how it works! And I’m sure you know *(x + 2) is equivalent to *(2 + x), so there!

Makes perfect sense doesn’t it!

arr[2] is equivalent to 2[arr]     !!!!!!!!!!!!!!!!