C code you should never use in production

I’ve been meaning to write this little trick down for a while, so while I remember to, here’s a stupid little C trick which amuses me.

Consider a C array:

char array[3] = {1,2,3};

To access element 3, you would use


This is just shorthand for a pointer dereference

*(array + 2)

This is just addition, which is associative, so it’s the exact equivalent of

*(2 + array)

which gives you


which is perfectly valid C.


To prove that, consider this simple program

void main()


char array[3] = {1,2,3};

printf("array[2]: %d. 2[array]: %d\n", array[2], 2[array]);

After compilation

array[2]: 3. 2[array]: 3


I would strongly caution against ever using this in production. Your colleagues will worry about you if they see it during a code review or when working on code you wrote. If you don’t think they would flag it, you should be worrying about them 🙂


Filed under code

5 Responses to C code you should never use in production

  1. Interesting. It reminds me of how in Clojure a map is a function of its keys, so eg. if you had map of names to values of some sort, you could write

    (people :kim)


    (:kim people)


    • kim

      Hi Ralph – what I know about Clojure is effectively zip, so could you elaborate a bit? This looks interesting and somewhat non-intuitive, so in order to aid my own limited understanding: “people” is the map in question, which is effectively a hash-table, or a Python dictionary?

  2. Pingback: C code that could get you fired | Kim van Wyk's Home on the Web

Leave a Reply

Your email address will not be published. Required fields are marked *