在开关盒中,char和int有什么区别? [英] What's the difference between char and int in a switch case?

查看:48
本文介绍了在开关盒中,char和int有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用C ++,在学习切换案例时,我对此表示怀疑.
如果在以下代码中使用int或char有什么区别:
int Fav_Car;
开关案例代码如下

I started C++ recently and while learning switch case, I got this doubt.
What's the difference if I use int or char in the following code :
int Fav_Car;
The switch case code is as follows

switch( Fav_Car ) {
    case '1' :
        cout<< "That's cool";
        break;
    case '2' :
        cout<< "Even mine!";
        break;
    default :
        cout<< "Oh";
        break;
}

运行程序时,我注意到使用int会返回默认大小写,而使用char则可以完美工作.为什么会这样?
而且,如果我使用 case'1': case"1":

When I ran the program, I noticed that using int returns me the default case and using char works perfectly. Why does it happen so?
And also, what's the difference if I use case '1' : and case "1" :

推荐答案

您的误解与 switch()构造无关,所有内容都与单引号'':如果您编写 1 ,则将得到值1的整数,将其放在单引号'1'中时,将得到ASCII的数值数字1的字符(这有点不精确,请参见下面的注释).该ASCII字符的数字值为十进制的 0x31 49 .现在想象一下之间的区别

Your misunderstanding has nothing to do with the switch() construct, it's all about the single quotes '': If you write 1, you get an integer of the value 1, when you put it in single quotes '1', you get the numeric value of the ASCII character for the digit 1 (this is a bit imprecise, see note below). That ASCII character has the numeric value of 0x31, or 49 in decimal. Now imagine the difference between

switch( Fav_Car ) {
    case 1 :
        cout<< "That's cool";
        break;
    case 2 :
        cout<< "Even mine!";
        break;
    default :
        cout<< "Oh";
        break;
}

switch( Fav_Car ) {
    case 49 :
        cout<< "That's cool";
        break;
    case 50 :
        cout<< "Even mine!";
        break;
    default :
        cout<< "Oh";
        break;
}

第二个与您发布的版本等效,我认为很清楚为什么它的行为与第一个版本大不相同.

The second one is equivalent to the version that you posted, and I think it's clear why it behaves very differently from the first version.

注意:
在大多数C ++实现中,虽然'1'会产生ASCII字符值,但并非必须如此.该实现可以自由使用其他一些字符代码,因此'1'的值实际上是实现定义的.它几乎可以是除零以外的任何内容(因为它用于终止字符串中的空字节).但是,大多数实现都使用ASCII编码,这就是为什么我在上面的文本中使用ASCII的原因.

Note:
While '1' yields an ASCII character value in most C++ implementations, that does not need to be the case. The implementation is free to use some other character code, so that the value of '1' is actually implementation defined. It could be virtually anything except zero (because that's used for the terminating null-byte in strings). However, most implementations do use ASCII encoding, which is why I assumed ASCII in the text above.

这篇关于在开关盒中,char和int有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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