A Curious Thing About Array Notation

It’s nuts. All through your C training when you learned about arrays, you were taught the format: array[x] where array is the name of the array and x is the element number. But this expression can also be written as x[array].

Mind. Blown.

This oddity is related to how arrays are dealt with internally by the compiler. As I’ve written about in my books and described in my online training, there is a strong relationship between arrays and pointers. It’s often said that array notation is a shortcut for pointers, though that’s not 100 percent accurate. Instead, it’s better to say that arrays translate into pointers easily. And I’ll add that using pointers is faster. Anyway.

#include <stdio.h>

int main()
{
    int a[5] = { 10, 20, 30, 40, 50 };

    printf("%d\n",a[3]);
    printf("%d\n",3[a]);

    return(0);
}

Here’s the output:

40
40

Both expressions a[3] and 3[a] reference the fourth element of array a[]. Upon learning such thing I freaked out. “What if I’ve been doing it wrong!”

Don’t worry: I must maintain that proper and consistent representation of an array in the C language is important. In the original K&R manual, arrays are written name[size]. That’s it and that’s how everyone should do it. In fact, you cannot declare an array like this:

int 5[a];

This statement generates a host of errors should you attempt to compile the code. But the expression 3[a] does in fact represent the fourth element of the array. How?

Internally, the compiler sees the name of the array as a base address. It’s not really a pointer, but the a in a[3] refers to a memory location. It’s similar to the pointer expression *(a+3).

When you reference an array element as 3[a], internally the compiler casts the expression as *(3+a). Therefore:

a[3] == 3[a] because *(a+3) == *(3+a)

I hope my explanation removes any puzzlement you may have over the 3[a] type of expression. In practical use, I strongly recommend that you write a[3] to keep your code consistent and readable. But you ever stumble across some joker who reverses his array notation for whatever reason, now you know he’s just being goofy.

5 thoughts on “A Curious Thing About Array Notation

  1. Saw it on Stack Overflow. Nothing on it in K&R. I’m curious if this addressing also works in other C-like languages.

  2. Works in C++, not surprisingly.

    int a[5] = { 10, 20, 30, 40, 50 };
    cout << a[3] << "\n";
    cout << 3[a] << "\n";

    No idea about Java (never used it) or C# (haven't used it for several years). Apparently Rust is also C-like but never used it either.

  3. Could you post the link to the Stack Overflow thread please. They are sometimes amusing and entertaining as long as you don’t expect definitive answers.

    How do I…?
    The answer is…
    Thanks, great answer.
    No, that’s wrong, the right answer is…
    You’re both wrong, the answer is…
    No, the first answer is correct…

    and so on…………….

Leave a Reply