Tuesday, 15 May 2018

c - With arrays, why is it the case that a[5] == 5[a]?



As Joel points out in podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]




Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]?


Answer



The C standard defines the [] operator as follows:



a[b] == *(a + b)



Therefore a[5] will evaluate to:



*(a + 5)



and 5[a] will evaluate to:



*(5 + a)


a is a pointer to the first element of the array. a[5] is the value that's 5 elements further from a, which is the same as *(a + 5), and from elementary school math we know those are equal (addition is commutative).


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...