C++ reversing indexer and name of array

This question already has an answer here:

  • With arrays, why is it the case that a[5] == 5[a]? 17 answers

  • The reason this is the case is because arr[n] == *(arr + n) .

    However, because addition is commutative, *(arr + n) == *(n + arr) . Thus, *(n + arr) == n[arr] == *(arr + n) == arr[n] .

    It might be worth mentioning that *(arr + n) is still a little misleading. In assembly it actually means *(arr + (n * s)) where s is sizeof arr[0] , but this is under the covers so you don't need to worry about it.


    I don't think this particular [ab-]use of the rules for pointer arithmetic has any particular name. It is simply falling out of the way pointer arithmetic is defined in C and C++. Neither of the two language standards makes any special attempt to prevent the reversal of the subscript and the pointer. For example, the relevant C++ rule is in 5.2.1 [expr.sub] paragraph 1:

    A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “array of T” or “pointer to T” and the other shall have unscoped enumeration or integral type. The result is of type “T.” The type “T” shall be a completely-defined object type. The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. —end note ], except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise.

    It may work to look for "C++ 5.2.1" or "C++ [expr.sub]" but the use of the reversal isn't that large beyond confusing people who haven't look long enough at C or C++.

    链接地址: http://www.djcxy.com/p/86740.html

    上一篇: C数组算术和指针

    下一篇: C ++反向索引器和数组名称