Can anyone explain to me what this particular print statement does in a loop?
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. an array that I didn't understand, cout <(i [ai]% N) [a + i-1] <"";
+3
sa_nyc
source
to share
1 answer
This is CBCPAT, a confusing but correct arithmetic trick.
Since subscribing to an array in C ++ (and C) is done using pointer arithmetic, if a
is an array and i
is an index (integer) then
a[i]
equivalent to
*(a + i)
and since addition is commutative, it is the same as
*(i + a)
which, in turn, can be written as
i[a]
I am. i.e. you are indexing an integer with an array (WTH?).
After getting familiar with this, you can easily rewrite the code to understand what it does: it is equivalent to
(a + i - 1)[(a - i)[i] % N]
which is just
(a + i - 1)[1 % N]
which in turn
(a + i - 1)[1 % 5],
i.e
*(a + i - 1 + 1)
which the
a[i]
Voila. Screw the programmer who wrote this shit.
+15
user529758
source
to share