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?

7
  • 5
    This must be a duplicate of a few dozen questions... Commented Jan 17, 2013 at 12:02
  • have a look here Commented Jan 17, 2013 at 12:02
  • A better question is for some user defined types that overload the operator [](int) would this work: 5[myType()] Commented Jan 17, 2013 at 12:07
  • 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 which has a cast-operator for int*. It does exactly what you think it might. Good times. Commented Jan 17, 2013 at 12:28
  • 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 Commented Jan 17, 2013 at 12:37

3 Answers 3

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]

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the main must return int :)
ok it's valid Microsoft C++ in that it compiles :)
I'm surprised that it doesn't also grab the letters after it and give you 0x003F4654, since you declared the variable x as an int rather than a char
3
int x = 1["WTF?"];

equals to

int x = "WTF?"[1];

84 is "T" ascii code

Comments

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].

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.