Monday, October 13, 2008

c/c++: array subscripting operator [ ]

Everybody knows that operator [] allows to specify the element of the array.
Using the knowledge about the arrays, which says that the elements of the array are stored sequentially in the memory we can recall that the elements of the array can be accessed using pointer arithmetic.

int a[] = {1,2,3};
std::cout << "First:" << *a << std::endl;
std::cout << "Second:" << *(a + 1) << std::endl;
std::cout << "Third:" << *(a + 2) << std::endl
So, the expression a[index] is equivalent to the expression *(a + index). According to arithmetic rules
*(a + index) == *(index + a)
What does that mean? That means that using the definition of operator [], which says the expression a[b] is equivalent to the expression *((a) + (b)), we can write
int a[] = {1,2,3};
std::cout << "First:" << 0[a] << std::endl;
std::cout << "Second:" << 1[a] << std::endl;
std::cout << "Third:" << 2[a] << std::endl
This is similar to the first listing and to the traditional style
int a[] = {1,2,3};
std::cout << "First:" << a[0] << std::endl;
std::cout << "Second:" << a[1] << std::endl;
std::cout << "Third:" << a[2] << std::endl

No comments: