1

For example, for the following code, I know that p is a pointer, which points to the first element of the array arr, and I also know that the array will degenerate into an array under certain conditions, but why can the [] operation be performed on the pointer here?

#include<iostream>
using namespace std;
int main()
{
  int arr[10];
  arr[3] = 10;
  int* p = arr;
  cout << p[3];
  return 0;
}

Is there any documentation for this?
run it online

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Kargath
  • 450
  • 5
  • 15
  • 1
    Sure there is a documentation, C++ is documented by the C++ standard. Relevant quote: http://eel.is/c++draft/expr.sub#2.sentence-5. Important part: _"The expression `E1[E2]` is identical (by definition) to `*((E1)+(E2))`..."_. – Daniel Langr Dec 02 '22 at 13:43
  • 1
    The roots of this go at least as far back as the [B](https://en.wikipedia.org/wiki/B_(programming_language)) language (1969). – molbdnilo Dec 02 '22 at 13:50
  • And since pointer arithmetic addition is commutative, p+3 is the same as 3+p, so is dereferencing those resulting pointers. Hence, `3[p]` is not just valid, but it's the same as `p[3]` – franji1 Dec 02 '22 at 14:11

1 Answers1

2

From the C++ 20 Standard (7.6.1.2 Subscripting)

1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall be a glvalue of type “array of T” or a prvalue of type “pointer to T” and the other shall be a prvalue of unscoped enumeration or integral type. The result is of type “T”. The type “T” shall be a completely-defined object type.62 The expression E1[E2] is identical (by definition) to *((E1)+(E2)), except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise. The expression E1 is sequenced before the expression E2.

That is when an array is used in this expression *((E1)+(E2)) then it is converted implicitly to pointer to its first element.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Looks like my search ability (and my patience) have regressed a bit, but I've decided to keep this question in order to preserve the answer =_= – Kargath Dec 02 '22 at 14:02