Recently saw the following chunk of code:
int main()
{
int a = 3;
0[&a] = a+a;//What is this???
}
Could anybody explain, what this means?
Recently saw the following chunk of code:
int main()
{
int a = 3;
0[&a] = a+a;//What is this???
}
Could anybody explain, what this means?
That is some ugly code -- but it's perfectly legal (in both C and C++).
As explained in this question (with this popular answer and my attempt to provide some historical context. the [] indexing operator is commutative, so
0[&a] = a+a;
is equivalent to:
(&a)[0] = a+a;
&a is the address of the int object a. The indexing operator takes a pointer operand and an integer operand. Typically the pointer is an array name (or equivalently, in this context, a pointer to the array's first element). But a single object can, for purposes of indexing and pointer arithmetic, be treated as an array with a single element.
The previous declaration is:
int a = 3;
The assignment treats the int object a as if it were a single-element array of int, and refers to that array's element 0 -- which happens to be the only element that exists.
The previous value of a is 3, so a+a is obviously 6.
So this:
int a = 3;
0[&a] = a+a;
is equivalent to this:
int a = 3;
a = a + a;
which is equivalent to:
int a = 3;
a = 6;
which ultimately is equivalent to this:
int a = 6;
In a typical professional software engineering environment, it's effectively equivalent to:
int a = 6; /* Please reject this submitted code and consider firing me. */
Array subscripting in C is a bit strange. The standard defines E1[E2] as equivalent to *(E1+E2). Of course, addition is commutative, so this is equivalent to *(E2+E1). Which makes it equivalent to E2[E1]...
With this in mind, your second line becomes:
(&a)[0] = a+a;
which you'll probably agree is equivalent to:
*(&a) = a+a;
or
a = a+a;