This question already has an answer here:
As I have learned, one can write the following code:
char *a = new char[50];
for (int i = 0; i < 50; ++i) {
i[a] = '5';
}
It compiles. It works. It does exactly the same as
char *a = new char[50];
for (int i = 0; i < 50; ++i) {
a[i] = '5';
}
Is it just because:
a[b]
is implemented as a macro*(a + b)
by default and the fact that both code samples are valid is just an accident/compiler specific- it's standardized somewhere and the outcome of such algorithms should be the same on every platform
It is reasonable to assume that addition should be commutative, but if we implement operator[]
in that way, we have made something else commutative, what might not be what we wanted.
The interesting fact is that there is no pointer[pointer]
operator, so operator[]
is not a macro.
I know it's bad. I know it's confusing the people who read the code. But I want to know if it's just an accident and it will not work in a distant land where unicorns have seven legs and horns are on their left cheek.
...and then commutativity of index and pointer takes hold. See your friendly neighbourhood C++ standard, section 5.2.1 in this version: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf
C++ standard, § 8.3.4, note 7 (page 185) (emphasis mine).
Here is what C++11 standard has to say:
So your assumption that
a[b]
is implemented as*(a + b)
is correct, except that it is implemented directly in the compiler, not as a macro.