Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this work? Illogical array access

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?

like image 414
untitled8468927 Avatar asked Jan 18 '12 13:01

untitled8468927


1 Answers

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.

like image 130
Adam Wright Avatar answered Oct 02 '22 08:10

Adam Wright