c++arrayspointerssyntaxsubscript-operator

is int[pointer-to-array] in the C++ - standard?


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:

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.


Solution

  • C++ standard, § 8.3.4, note 7 (page 185) (emphasis mine).

    Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetric appearance, subscripting is a commutative operation.