About pointers

Hi, I found a syntax that I hadn't known before. Can somebody explain to me WHY this works?

1
2
3
4
5
6
#include <iostream>

int main() {
  const char* cp = "abcdefgh";
  cout << (4)[cp];
}


e


Thanks in advance.
Last edited on
It's one of those things you either know about C/C++ or you don't know.

if p is a pointer then p[4] means *(p+4) and because the + operator is commutative (spelling) then p+4 is the same as 4+p. So p[4] is the same as 4[p] in array indexing.
Note one of the terms must be a pointer.

In the original post, the () around the 4 is not necessary - so it could have been written as
cout << 4[p]
Oh, that's not too difficult and I should have been able to figure it out by myself, sorry.

Anyway thank you for the very good explanation.
Topic archived. No new replies allowed.