Wh开发者_如何学Pythony 2[a] can be compiled if only declare int a[3] in C.
1 #include <stdio.h>
2
3 int main(int argc, char **argv)
4 {
5 int a[3] = {1, 2, 3};
6 printf("a[2] is: %d\n", a[2]);
7 printf("2[a] is: %d\n", 2[a]);
8
9 return 0;
10 }
And the output both 3, how to explain it?
Because a[2]
is just syntactic sugar for *(a+2)
, which is the same as *(2+a)
or 2[a]
.
Because all a[2]
means in C is *(a + 2)
, and so *(2 + a)
works just as well, which could also be written 2[a]
.
An expression is composed of one or more operands. The simplest form of an expression consists of a single literal constant or object. The result, in general, is the operand's rvalue.
As per the C 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))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
So, a[b]
is equivalent to *(a+b)
and b[a]
. where a
and b
can be any expression.
精彩评论