The dark orders of C++
There is one dark corner of the C++ language that is rarely touched by sunlight, and if a piece of code from these depths surfaces by any chance, a gang of hardcore developers immediately jumps on it and refactors it into digestible bits and bytes. Let’s consider, for example, the very simple case of why the a[2]
and 2[a]
expressions are equivalent when in C++, and a
is an array of objects:
int main() { int a[16] = {0}; a[2] = 3; 3[a] = 4; }
The preceding piece of code, despite the fact that it looks ugly, actually compiles. The reason is the following: in C++, the operator []
array subscript is defined in terms of pointer arithmetic. The a[i]
expression is translated by the compiler into *(a + i)
, where a
is a pointer to the first element of the array and i
is the index. The i[a]
expression at the end is also translated to the *(i + a)
expression, where i
is the index and a
is...