在C ++中用字符串索引的整数 [英] integer indexed with a string in c++

查看:160
本文介绍了在C ++中用字符串索引的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在C数组中为什么如此? a [5] == 5 [a]

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 chars (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆