integer indexed with a string in c++

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?


Array subscript operator is commutative. It's equivalent to int x = "WTF?"[1]; Here, "WTF?" is an array of 5 char s (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]


int x = 1["WTF?"];

equals to

int x = "WTF?"[1];

84 is "T" ascii code


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

链接地址: http://www.djcxy.com/p/86732.html

上一篇: 为什么在c ++中x [y] == y [x]?

下一篇: 整数用c ++中的字符串索引