Search code examples
c++arrayspointersimplicit-conversionpointer-arithmetic

Is there a conversion from pointer to array?


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


Solution

  • 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.