Saturday, February 27, 2010

Why can you write arr[n] == n[arr] in C ?

Try the following program in C :

#include <stdio.h>

int main () {
  int arr[] = {42};
  printf("%d", arr[0] == 0[arr]);
  return 0;
}

The above program prints out 1...ie, true.

But why...?

Well the reason the above works is because of how arrays are represented in C. In C, when referencing an array, you're just referencing a pointer to the first element :

int arr[] = {42, 39};
int x = arr[0];
int y = *(arr + 0);
// x == y

In the *(arr + 0) example, we are accessing the first element of the array by dereferencing the pointer to the first element arr plus the 0 offset.

int arr[] = {42, 39};
int x = arr[1];
int y = *(arr + 1);
// x == y

In the above example, we are accessing the second element with index 1.

Therefore, if *(arr + 1) evaluates to arr[1], then surely *(1 + arr) evaluates to 1[arr] according to elementary math...because addition is commutative, which means that the order of the operands does not matter, as it produces the same result.

The reason for this is because since C was designed back in the 70s, computers did not have much memory and thus the C compiler didn't do much syntax checking. Therefore, something like arr[i] was blindly translated to *(arr + i)