在C ++中用字符串索引的整数 [英] integer indexed with a string in c++
问题描述
Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]
这怎么可能是有效的C ++?
How is it possible that this is valid C++?
void main()
{
int x = 1["WTF?"];
}
在VC ++ 10上,它将进行编译,并且在调试模式下,语句后的x
值为84.
On VC++10 this compiles and in debug mode the value of x
is 84 after the statement.
这是怎么回事?
推荐答案
数组下标运算符是可交换的.等效于int x = "WTF?"[1];
在这里,"WTF?"
是5个char
s的数组(它包含空终止符),并且[1]
给我们第二个字符,它是'T'
-隐式转换为int
给出值84.
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:代码段不是有效的C ++,实际上-main
必须返回int
.
Offtopic: The code snippet isn't valid C++, actually - main
must return int
.
您可以在此处阅读更多深入的讨论:在C数组为何如此? a [5] == 5 [a]
You can read more in-depth discussion here: In C arrays why is this true? a[5] == 5[a]
这篇关于在C ++中用字符串索引的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!