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?
Assume
p
is a pointer or array, andn
is an integer. When the compiler sees this:It logically interprets that expression as:
So when it sees this:
The compiler treats it as:
Which is algebraically the same as
*(p+n)
Hence:
p[n] == n[p]