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};
printf("%d",arr[2]);

(OUTPUT : 7)

But did you know that even this code works :

int arr[3] = {5,6,7};
printf("%d",2[arr]);

(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]     !!!!!!!!!!!!!!!!

Advertisement

4 thoughts on “Interesting C code

  1. Prashanth says:

    //comment

  2. Muktabh says:

    Nice post 🙂

  3. Harsh says:

    /* Nice one */

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: