With arrays, why is it the case that a[5] == 5[a]?
As Joel points out in Stack Overflow 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]
?
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).
Because array access is defined in terms of pointers. a[i]
is defined to mean *(a + i)
, which is commutative.
And, of course
("ABCD"[2] == 2["ABCD"]) && (2["ABCD"] == 'C') && ("ABCD"[2] == 'C')
The main reason for this was that back in the 70's when C was designed, computers didn't have much memory (64KB was a lot), so the C compiler didn't do much syntax checking. Hence " X[Y]
" was rather blindly translated into " *(X+Y)
"
This also explains the " +=
" and " ++
" syntaxes. Everything in the form " A = B + C
" had the same compiled form. But, if B was the same object as A, then an assembly level optimization was available. But the compiler wasn't bright enough to recognize it, so the developer had to ( A += C
). Similarly, if C
was 1
, a different assembly level optimization was available, and again the developer had to make it explicit, because the compiler didn't recognize it. (More recently compilers do, so those syntaxes are largely unnecessary these days)
上一篇: 性能优化策略的最后手段