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] << " ";

1

1 Answer 1

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.

2
  • 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, 2013 at 6:02
  • 3
    +1 solely for the last sentence. I'd +1 again for the great explanation if I could. Feb 15, 2013 at 6:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.