#include <iostream>
using namespace std;
int main(void) {
cout << 2["abc"] << endl;
return 0;
}
$ g++ test.cpp -o test
$ ./test
c
What the C++ syntax is? Why it work? Can someone explain it?
#include <iostream>
using namespace std;
int main(void) {
cout << 2["abc"] << endl;
return 0;
}
$ g++ test.cpp -o test
$ ./test
c
What the C++ syntax is? Why it work? Can someone explain it?
Because a[b]
is *(a + b)
1 and b[a]
is *(b + a)
, and +
is commutative.
1 unless overloaded and other shenanigans.
Array indexing is cummutative. See this and this.
In your case, narrow string literals are basically const array of characters. Which makes:
cout << 2["abc"] << endl;
same as
cout << "abc"[2] << endl;
To partially quote (emphasis mine):
...A narrow string literal has type “array of n const char”...
A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall be a glvalue of type “array of T” or a prvalue of type “pointer to T” and the other shall be a prvalue of unscoped enumeration or integral type. The result is of type “T”....
Note: it only works for arrays. When you do:
struct Foo
{
Foo& operator[](std::size_t index) { return *this; }
};
Foo foo;
Below will work work because its actually calling foo.operator[] (2)
;
Foo f;
f[2]; //Calls foo.operator[] (2);
Below will not work because, one of the expressions is not an array, hence the compiler proceeds to find a suitable 2.operator[] (foo)
, which would fail because integral types have no member functions.
2[f]; //will not work