Meaning of 1[pointer] in C++?

162 Views Asked by At

Reading cppreference I found this example:

int a[4] = {1, 2, 3, 4};
int* p = &a[2];
std::cout << p[1] << p[-1] << 1[p] << (-1)[p] << '\n'; // 4242

I am confused about the meaning of 1[p] and (-1)[p]. Asking for help elsewhere I was told: "1[ptr] is equivalent to *(1 * sizeof(T) + ptr)". So I understand mechanically why it outputs 4242, but I find it hard to reason about. As it's nonsensical to put a pointer in square brackets usually, and is an error by itself:

[cling]$ 1[p]
(int) 4
[cling]$ [p]
input_line_15:2:3: error: 'p' cannot be captured because it does not have
      automatic storage duration
 [p]
  ^

Is this just a special case of the syntax I should just memorize, or am I misunderstanding some logic behind the statement?

1

There are 1 best solutions below

0
On BEST ANSWER

Assume p is a pointer or array, and n is an integer. When the compiler sees this:

p[n]

It logically interprets that expression as:

*(p+n)

So when it sees this:

n[p]

The compiler treats it as:

*(n+p)

Which is algebraically the same as *(p+n)

Hence: p[n] == n[p]