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

3
  • 1
    Sure there is a documentation, C++ is documented by the C++ standard. Relevant quote: eel.is/c++draft/expr.sub#2.sentence-5. Important part: "The expression E1[E2] is identical (by definition) to *((E1)+(E2))...". Commented Dec 2, 2022 at 13:43
  • 1
    The roots of this go at least as far back as the B language (1969). Commented Dec 2, 2022 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] Commented Dec 2, 2022 at 14:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 =_=

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.