Reputation: 981
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] << " ";
Upvotes: 3
Views: 208
Reputation:
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.
Upvotes: 15