Today I wanted to propose to students a very short and stupid code as follows
# include <iostream>
int main()
{
int a[] {10, 20, 30, 40};
for(int k=0; k != 4; ++k) std::cout << ++a[k] << ' ';
std::cout << std::endl;
}
in order to show how the ++
prefix operator acts in an expression.
I inadvertently mistyped the code, ending up with the following line, in place of the one shown above:
for(int k=0; k != 4; ++k) std::cout << ++k[a] << ' ';
shortly: swapping k
and a
in the operand of ++
.
Well... not only this is compiled, but it gives also the correct results.
How this could be understood? Is the index of the loop interpreted as an iterator over the array a
? Or what else?