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?
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?
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 thatE1[E2]
is identical to(*((E1)+(E2)))
.
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