Tuesday, December 9, 2014

a[3] == 3[a] : True, False, or Syntax Error?

In C, if we have an array :
unsigned char a[5]; 

Is the following expression :
a[3] == 3[a]
true or false, or its a syntax Error ?

It's true because of Pointer Arithmetic.
This is the direct artifact of arrays behaving as pointers, "a" is a memory address. "a[3]" is the value that's 3 elements further from "a". The address of this element is "a + 3".
This is equal to offset "
a" from "3" elements at the beginning of the address space "3 + a".

Simpler, the C standard defines the [] operator as follows:
a[b] == *(a + b)
Therefore a[3] will evaluate to:
*(a + 3)
and 3[a] will evaluate to:
*(3 + a)
and this is why those are equal.

No comments: