0

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?

yrom1
  • 27
  • 1
  • 1
  • 5
  • 2
    There's really nothing to it aside from them choosing to make the operation commutative in that way. You don't really need to know it. It's more a fun trivia fact than something that you'll ever want to write yourself or have good reason to expect to read from anyone else's code. – Nathan Pierson Apr 29 '22 at 02:22
  • `[p]` is the equivalent of `p[]` which is also invalid. Does that clear up the confusion? Have you seen: https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a – NathanOliver Apr 29 '22 at 02:24
  • Did you read point 1 of the section to which you linked? That plus the first sentence after the list explains it as well as I could. (So no need for me to waste my time if that explanation is not enough.) – JaMiT Apr 29 '22 at 02:24
  • `1[pointer]` means the same as `pointer[1]`. Blame Dennis Ritchie. – user207421 Apr 29 '22 at 02:27

1 Answers1

4

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]

selbie
  • 100,020
  • 15
  • 103
  • 173