Description
I found a minor omission in the latest version of C++ standard. http://eel.is/c++draft/dcl.array, note 6 say:
[ Note: Except where it has been declared for a class (http://eel.is/c++draft/over.sub), the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)) (http://eel.is/c++draft/expr.sub). 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 ofE1. Therefore, despite its asymmetric appearance, subscripting is a commutative operation. — end note ]
In essence, this says that the following function:
int foo()
{
int a[]={1,2,3,4,5};
return 2[a];
}
should compile.
The reference to http://eel.is/c++draft/over.sub makes it clear that what is meant here is overloaded subscript operator within a class, not an operator with a class type as a parameter.
The issue here is that operator [] may also be global, and those would also be an "exception". Perhaps we should rewrite this note along the following lines:
[ Note: Except where it has been declared for a class (http://eel.is/c++draft/over.sub) or in a global or namespace scope, the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)) (http://eel.is/c++draft/expr.sub). 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 ofE1. Therefore, despite its asymmetric appearance, subscripting is a commutative operation. — end note ]
Another alternative would be:
[ Note: For C arrays, the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)) (http://eel.is/c++draft/expr.sub). 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 ofE1. Therefore, despite its asymmetric appearance, subscripting for C arrays is a commutative operation. — end note ]
Activity
tkoeppe commentedon Apr 9, 2017
What do you mean by "operator [] may also be global"? [over.sub] says:
levmin commentedon Apr 10, 2017
Yes, I see now that operator [] cannot be global. Probably my second alternative would be a little more clear than what's currently in the standard, but I am not sure if that would be a discussion worth having. I am closing the issue.
jwakely commentedon Apr 10, 2017
That suggestion would not have been an improvement IMO. "C array" is not a defined term. It only occurs once in the standard, in a footnote in [valarray.cons] (and that should probably be fixed). The subscript operator is also valid for pointers, not just arrays.
levmin commentedon Apr 10, 2017
tkoeppe commentedon Apr 10, 2017
This is well out of scope for this editorial issue tracker. (If you'd like to pursue this, please consider starting on the std-proposals mailing list.)