为什么switch语句不能应用于字符串? [英] Why switch statement cannot be applied on strings?

查看:695
本文介绍了为什么switch语句不能应用于字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
    switch(std::string("raj")) //Compilation error - switch expression of type illegal 
    {
    case"sda":
    }

}


推荐答案

之所以与类型系统有关。 C / C ++不真正支持字符串作为类型。它支持一个常量char数组的想法,但它并不真正完全理解一个字符串的概念。

The reason why has to do with the type system. C/C++ doesn't really support strings as a type. It does support the idea of a constant char array but it doesn't really fully understand the notion of a string.

为了生成switch语句的代码,编译器必须理解两个值相等的含义。对于像int和枚举这样的项目,这是一个微不足道的比较。但是编译器应该如何比较2个字符串值?区分大小写,不敏感,文化意识等。没有一个字符串的完全意识,这不能准确地回答。

In order to generate the code for a switch statement the compiler must understand what it means for two values to be equal. For items like ints and enums, this is a trivial bit comparison. But how should the compiler compare 2 string values? Case sensitive, insensitive, culture aware, etc ... Without a full awareness of a string this cannot be accurately answered.

此外,C / C ++ switch语句通常生成为分支表。为字符串样式开关生成分支表不是那么容易。

Additionally, C/C++ switch statements are typically generated as branch tables. It's not nearly as easy to generate a branch table for a string style switch.

这篇关于为什么switch语句不能应用于字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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