The index operator belongs to the class of postfix operators. It is defined as follows (C ++ Standard, Section 5.2.1 Subscripting)
1 A post fi x expression in square brackets is a post fi x expression.
That is, the postfix expression is followed by an expression in square brackets.
In this expression
i--[a]
i-- is a post-decrement operator, which belongs to the class of postfix expressions. So, there is
i-- [a] | | постфиксное выражение выражение в квадратных скобках
So from the point of view of syntax, this expression is absolutely correct.
Further in the same citation from the standard there is a continuation
1 ... one of the expressions of the “or of the pointer and the number of expressions” The “T.” The type “T.” has been completely de fi ned object type.64 The expression E1 [E2] is identical to * ((E1) + (E2))
from which it follows that one of the expressions must be either an array or a pointer, and the other expression is an enumeration or an integer type. Which of these two expressions which type should have no significance, since by definition the expression E1[E2] equivalent to the expression *((E1) + (E2)) .
In C ++, you can write an even more elaborate construct by adding a plus sign in front of the array name. For example,
#include <iostream> int main() { int a[] = { 0, 2, 4, 6, 8 }; int i = 0; std::cout << i++[+a] << std::endl; return 0; }
In C, such a construction i++[+a] will not be compiled, since in C, unlike C ++, you cannot use unary plus to the array name.
In C ++, the user can also overload the index operator for the initialization list in curly braces. For example,
#include <iostream> #include <initializer_list> #include <numeric> int main() { struct A { long long int operator []( std::initializer_list<int> l ) const { return std::accumulate( l.begin(), l.end(), 0ll ); } }; std::cout << A()[{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }] << std::endl; return 0; }
Output of the program to the console
55