1

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?

gorill
  • 1,623
  • 3
  • 20
  • 29

2 Answers2

7

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. */
Community
  • 1
  • 1
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Of which Stroustrup writes "Such cleverness has no place in production code." (CPL4 7.4.1) – dhavenith Aug 30 '13 at 23:21
  • @dhavenith: Years ago, when I was first learning C, I wrote `#define EVER ;;` ... `for (EVER) ...`. I thought it was very clever. I *still* think it's very clever -- I just no longer think that's a good thing. – Keith Thompson Aug 30 '13 at 23:32
4

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;
nickie
  • 5,608
  • 2
  • 23
  • 37