5

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

How is it possible that this is valid C++?

void main()
{
  int x = 1["WTF?"];
}

On VC++10 this compiles and in debug mode the value of x is 84 after the statement.

What's going on?

Community
  • 1
  • 1
ehremo
  • 387
  • 2
  • 8
  • 5
    This must be a duplicate of a few dozen questions... – Sergey Kalinichenko Jan 17 '13 at 12:02
  • have a look [here](http://stackoverflow.com/a/1995156/238902) – default Jan 17 '13 at 12:02
  • A better question is for some user defined types that overload the `operator [](int)` would this work: `5[myType()]` – paul23 Jan 17 '13 at 12:07
  • sorry for duplicate question, didn't know what to search for – ehremo Jan 17 '13 at 12:27
  • 1
    @paul23 the intrinsic scalers are short-cut by the compiler. So not directly. However... never say never. Check out [this useless piece of code](http://ideone.com/bYrlXf) which has a cast-operator for `int*`. It does exactly what you think it might. Good times. – WhozCraig Jan 17 '13 at 12:28
  • @WhoizCraig That's awesome, hehe. – jrok Jan 17 '13 at 12:33
  • 1
    I sometimes to this with index variables just to see the double take on peer-programmers faces. you know, a complicated for-loop and buried in the middle of it: `i++[arName]` and such. Keeps them on their toes =P – WhozCraig Jan 17 '13 at 12:37

3 Answers3

9

Array subscript operator is commutative. It's equivalent to int x = "WTF?"[1]; Here, "WTF?" is an array of 5 chars (it includes null terminator), and [1] gives us the second char, which is 'T' - implicitly converted to int it gives value 84.

Offtopic: The code snippet isn't valid C++, actually - main must return int.

You can read more in-depth discussion here: In C arrays why is this true? a[5] == 5[a]

Community
  • 1
  • 1
jrok
  • 54,456
  • 9
  • 109
  • 141
3
int x = 1["WTF?"];

equals to

int x = "WTF?"[1];

84 is "T" ascii code

Damask
  • 1,754
  • 1
  • 13
  • 24
1

The reason why this works is that when the built-in operator [] is applied to a pointer and an int, a[b] is equivalent to *(a+b). Which (addition being commutative) is equivalent to *(b+a), which, by definition of [], is equivalent to b[a].

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455