c++ switch 支持的类型

以前一直没有注意switch表达式中的标签支持哪些类型,使用了自定义类型编译不过,才去注意下switch支持哪些类型,网上说Java支持的有byte、short、int、char(JDK1.6),还有枚举类型,但是在JDK1.7后添加了对String类型的判断,为了弄明白C++支持哪些我还是查了下比较权威是书籍。

以下摘抄C++ Primer Plus,可以知道c++中switch 表达式支持int型char型,还有enum型 ,当为枚举类型时会强制转换为int型。是否还支持其他类型还需要查阅更多的资料。

switch (integer-expression)
{
case label1 : statement(s)
case label2 : statement(s)
...
default : statement(s)
}


A C++ switch statement acts as a routing device that tells the computer which line of code to execute next. On reaching a switch statement, a program jumps to the line labeled with the value corresponding to the value of integer-expression. For example, if integerexpression has the value 4, the program goes to the line that has a case 4: label. The value integer-expression, as the name suggests, must be an expression that reduces to an integer value. Also, each label must be an integer constant expression. Most often, labels are simple int or char constants, such as 1 or ‘q’, or enumerators. If integer-expression doesn’t match any of the labels, the program jumps to the line labeled default. The default label is optional. If you omit it and there is no match, the program jumps to the next statement following the switch

Listing 6.11 illustrates using enum to define a set of related constants and then using the constants in a switch statement. In general, cin doesn’t recognize enumerated types (it can’t know how you will define them), so the program reads the choice as an int. When the switch statement compares the int value to an enumerator case label, it promotes the enumerator to int. Also, the enumerators are promoted to type int in the while loop test condition.

 

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值