以前一直没有注意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.