3

When I read asterisk source code, I found a code line like this:

#define ARRAY_LEN(a) (size_t) (sizeof(a) / sizeof(0[a]))

I often use a[0] or (*a), but they use (0[a]). Could you please help me explain more clearly about this?

M.M
  • 138,810
  • 21
  • 208
  • 365
GSP
  • 574
  • 3
  • 7
  • 34
  • A good question IMO. Pointer arithmetics is an horrible pitfall in C, and understanding better how it works is a good idea. – kuroi neko Sep 10 '15 at 02:31
  • 3
    This has many dups here already. – too honest for this site Sep 10 '15 at 02:41
  • 2
    Inside a macro this actually saves 2 characters of typing: `a[0]` could be incorrect, so the options are `(a)[0]` or `0[a]`. Of course there is also `*(a)`. – M.M Sep 10 '15 at 02:44
  • 4
    [With C arrays, why is it the case that `a[5] == 5[a]`?](http://stackoverflow.com/q/381542/995714) – phuclv Sep 10 '15 at 03:46
  • 1
    @M.M I would strongly recommend programmers who don't like typing to change career. Programming involves a whole lot of typing. Programmers who obfuscate their programs into unreadable crap, in order to save typing 2 characters should change career anyway, or have someone force them to change career. – Lundin Sep 10 '15 at 06:55

2 Answers2

7

a[0] is translated by the compiler as *(a+0). 0[a] is translated as *(0+a). Hence, a[0] and 0[a] are equivalent.

From the C99 standard:

6.5.2.1 Array subscripting

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

Arrays are symmetric and that means arr[idx] and idx[arr] are completely same to the compiler.

Therefore, sizeof(idx[arr]) is the byte size of the idx'th element of the array arr

Imobilis
  • 1,475
  • 8
  • 29