Why does this work? Illogical array access

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

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?


In simplistic terms, the access of an array element in C (and in C++, when [] isn't overloaded) is as follows:

x[i] = *(x + i)

So, with this and a little bit of arithmetic...

  foo[i][bar]
= (foo[i])[bar]
= (*(foo + i))[bar]
= *((*(foo + i)) + bar)
= *(bar + (*(foo + i)))
= bar[*(foo + i)]
= bar[foo[i]]

Don't use this "fact" though. As you've seen, it makes the code unreadable, and unreadable code is unmaintainable.

链接地址: http://www.djcxy.com/p/15212.html

上一篇: 在C中,i ++和++ i之间有性能差异吗?

下一篇: 为什么这个工作? 不合逻辑的数组访问