#include "stdio.h"
const char OPTION = (char)(unsigned char)253;
int main(int argc, char* argv[])
{
unsigned char c = 253;
switch (c)
{
case OPTION:
printf("option\n");
break;
default:
printf("unknown\n");
break;
}
return 0;
}
当查看C++标准(N3690 2013-05-05)时,我看到了一个关于switch的条款:
6.4.2 The switch statement
2 The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type. Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:
case constant-expression :
where the constant-expression shall be a converted constant expression (5.19) of the promoted type of the switch condition. No two of the case constants in the same switch shall have the same value after conversion to the promoted type of the switch condition.
所引用的转换条款:
4 标准转换
2 [ 注:在多种情况下,具有给定类型的表达式将被隐式转换为其他类型:
[...]
— 在 switch 语句的表达式中使用时。目标类型是整数型(6.4)。
[...]
—注释结束]
变量 c 的类型是无符号字符型,它是一种整数类型。因此不需要进行提升!?
如果提升类型是 unsigned char
,我会期望像 c == (unsigned char)OPTION
这样的比较结果是 true。如果提升类型是 int
,我会期望像 (int)c == (int)OPTION
这样的比较结果显然是 false。
我的问题是:上面的程序中使用了哪种提升类型?C 和 C++ 标准中的相关条款是什么?
OPTION
不是整数常量(不能用作switch
标签)。 - mafso(char)(unsigned char)253
替换case OPTION
(如果char
是有符号的话可能未定义),那么在C99/C11中,所有东西都会被提升为int
(只要unsigned char
总是适合于int
,这对于每个平台来说都是成立的,我想)。整数提升在C99/C11 §6.3.1.1(2)中有定义;§6.8.4.2“switch
语句”也可能相关。 - mafso