2010/01/03

In C, a[5] = 5[a], what the fxxk?

In a famous programmers' Q&A website Stack Overflow, I just found this strange C feature that I've never seen before.


int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printf("a[5]=%d\n", a[5]);
printf("5[a]=%d\n", 5[a]);

And a[5] is the same as 5[a], it's true! I found this feature in Standard C(C89). Wow. Because a[i] is defined to be the same as *((a) + (i)), where a the array identifier appearing in an expression will be converted to &a[0] except used as an operand of the sizeof or address (&) operators.

1 comment:

  1. Anonymous9/2/10 19:21

    Ccc, that's really cool. I never thought about that...

    ReplyDelete