cout << i[j[a]];
cout << j[i[a]];
In C++, the X[Y]
notation is lexically equivalent to *(X+Y)
:
[C++11: 5.2.1/1]:
[..] The expression E1[E2]
is identical (by definition) to *((E1)+(E2))
[..]
That means that Y[X]
is equivalent to *(Y+X)
, which is the same as *(X+Y)
since addition is commutative.
For some reason, the author has decided to try to be "clever" by writing this confusing code.
By commutativity and the definition for X[Y]
alone:
i[j[a]] => i[*(j+a)] => *(i+*(j+a)) => *(*(a+j)+i) => *(a[j] + i) => a[j][i]
j[i[a]] => j[*(i+a)] => *(j+*(i+a)) => *(*(a+i)+j) => *(a[i] + j) => a[i][j]
Your cout
statements are, then, equivalent to:
cout << a[j][i];
cout << a[i][j];
In any case, the loop attempts to read past the array bounds because there are only 5
integers in each element of the array a
, whereas your inner loop attempts to go all the way up to 10
.
The practical result of this is undefined, so you could get silent success, silent failure, arbitrary values, a segmentation fault, a power cut, a black hole, a pony for Christmas, a toe amputation or a new bike.
Even when the loop condition is fixed, note that the first statement is semantically incorrect (assuming you continue to ascribe the first dimension to the outer loop and the second dimension to the inner loop).