Friday, March 31, 2006

Commutativity of [] operator in C

Standard acknowledgement crap: I was enlightened about the following by a book I was reading while very bored. Hehe.

Consider the following program written in C.


/* program 1 */
#include <stdio.h>

int main()
{
   char *s=&"Hello world!!\n"[0];
   printf("%s\n",s);
   return 0;
}



Being so short, it is quite intuitive what this program does. This program will print out "Hello world!!" and a new line.

Now, consider the following program.


/* program 2 */
#include <stdio.h>

int main()
{
   char *s=&0["Hello world!!\n"];
   printf("%s\n",s);
   return 0;
}



Question: Does this program run? Answer: Yes, it does. Not only does Program #2 compile without any errors or warnings under GCC, it runs equivalently to Program #1 above.

Similar examples can be derived easily. To illustrate my point, here's another working program.


/* program 3 */
#include <stdio.h>

int main()
{
   int a[1];
   
   a[0]=5;
   printf("%d\n",*(&0[a]));
   
   return 0;
}



Next question: Does this have any application? Answer: No. It simply looks fun.

No comments: