开发者

Why 2[a] can pass compiling if only declare int a[3] in C

开发者 https://www.devze.com 2023-02-27 05:50 出处:网络
Wh开发者_如何学Pythony 2[a] can be compiled if only declare int a[3] in C. 1#include <stdio.h>

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号