When I was writing a program, I made a typo. I have wrote i[data]
instead data[i]
. However the program was successful compiled and worked right.
Operator[] behavior with arrays:
#include <iostream>
using namespace std;
int main()
{
int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << data[6] << endl; // prints 6
cout << 6[data]; // prints 6
return 0;
}
Similar operator[] behavior with pointers:
#include <iostream>
using namespace std;
int main()
{
char* str = "Hello, world!";
cout << str[9] << endl; //prints 'r'
cout << 9[str]; //prints 'r'
return 0;
}
Why data[i]
equals i[data]
?