A friend of mine is learning C++ for the first time, and sent me this snippet:
int foo[] = { 3, 38, 38, 0, 19, 21, 3, 11, 19, 42 };
char bar[] = " abcdefghijklmnopqrstuvwxyz01234567890+-,.!?-_";
for (int i = 0; i < 10; ++i) {
std::cout << foo[i][bar];
}
At a glance, I told him it won't work - I thought it wouldn't compile, or would at least result in an access violation, as foo
isn't a two-dimensional array, to which he replied that it does.
I tried for myself, and to my surprise, the snippet ran perfectly fine. The question is: why?
According to logic, common sense and good practice, the syntax should be bar[foo[i]]
.
I'm ashamed to admit that I have no idea what's going on. What makes foo[i][bar]
valid syntax in this case?