3
int a[] = { 1, 2, 3, 4, 5 };
const int N = sizeof(a)/sizeof(a[0]);
cout<<N<<endl;

for (int i = 0; i < N; ++i)
{
    cout << (i[a-i]%N)[a+i-1] << " ";
}

//It prints 1 2 3 4 5 i.e. the array what I didnt understand was cout << (i[a-i]%N)[a+i-1] << " ";

sa_nyc
  • 971
  • 1
  • 13
  • 23

1 Answers1

15

This is the CBCPAT, the Confusing But Correct Pointer Arithmetic Trick.

Since array subscription in C++ (and C) is done using pointer arithmetic, if a is an array and i is the index (an integer), then

a[i]

is equivalent to

*(a + i)

and since addition is commutative, this is the same as

*(i + a)

which in turn can be written as

i[a]

i. e. you're indexing the integer with the array (WTH?).

After having learnt this, you can easily rewrite the code to understand what it does: it is equivalent with

(a + i - 1)[(a - i)[i] % N]

which is just

(a + i - 1)[1 % N]

which is in turn

(a + i - 1)[1 % 5],

that is

*(a + i - 1 + 1)

which is

a[i]

Voilà. Screw the programmer who wrote this crap.

  • 7
    Note also, that it will work only if the first element of the table is equal to 1. `(a - i)[i]` written sanely is `a[i - i]` = `a[0]` = 1 (in this case). Anyway, I would sentence the programmer, who wrote this code to installing Windows 7 from floppy discs, at least ten times. – Spook Feb 15 '13 at 06:02
  • 3
    +1 solely for the last sentence. I'd +1 again for the great explanation if I could. – Cody Gray - on strike Feb 15 '13 at 06:10