array] in the C++

This question already has an answer here:

  • With arrays, why is it the case that a[5] == 5[a]? 17 answers
  • Why does x[y] == y[x] in c++? [duplicate] 3 answers

  • C++ standard, § 8.3.4, note 7 (page 185) (emphasis mine).

    Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)) . Because of the conversion rules that apply to + , if E1 is an array and E2 an integer, then E1[E2] refers to the E2 -th member of E1 . Therefore, despite its asymmetric appearance, subscripting is a commutative operation .


    Here is what C++11 standard has to say:

    Note: Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)) . Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2 -th member of E1 . Therefore, despite its asymmetric appearance, subscripting is a commutative operation. (emphasis is added).

    So your assumption that a[b] is implemented as *(a + b) is correct, except that it is implemented directly in the compiler, not as a macro.


    The expression E1[E2] is identical (by definition) to *((E1)+(E2))

    ...and then commutativity of index and pointer takes hold. See your friendly neighbourhood C++ standard, section 5.2.1 in this version: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf

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

    上一篇: 为什么这个代码片段可以在C中编译?

    下一篇: 数组]在C ++中