Victor Schubert’s personal page

Reversed Array Subscripting in C/C++

Ok, so this one is about something I'd qualify as a party trick: it's fun to do and usually very few people understand why it works. I seriously advise against ever doing that in real code as it makes your code a lot more confusing.

If you've done some C or C++ before, you certainly know how arrays work and how you access their elements with the subscript operator, using the following syntax.

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    int array[] = {2, 3, 5, 7}; /* `array' is now an array of four integers */

    printf("%d\n", array[2]); /* will print `5' */
    return EXIT_SUCCESS;
}

Once compiled, this very short snippet will allocate an array of four integers initialized with some values, read the third element and print it to the standard output. But now let us alter that code just a little bit.

printf("%s\n", 2[array]);

Ok. What in hell is that? You can try to compile it and it will still print 11. Enable the warnings and you'll see your compiler's not even complaining! The fact is: this is an absolutely valid and absolutely equivalent code. It does make some sense when you look how the subscript operator works behind the scenes. According to the May 13, 1988 ANSI C Standard Draft the subscript operator is defined as so.

The definition of the subscript operator [] is that E1[E2] is identical to (*(E1+(E2))).

This means something very interesting. Since array[n] is equivalent to *(array + n) and because addition is commutative, then *(array + n) is the same as *(n + array), which according to the standard is equivalent to n[array].