简体   繁体   English

使用size_t的负值切换

[英]switch with a negative value for size_t

If I have the following snippet: 如果我有以下代码段:

size_t num = -1;

switch(num) {
    case -1:
        printf("Minus one!\n");
        break;
    default:
        printf("Not minus one!\n");
}

Why is it that the program prints Minus One! 为什么程序会打印Minus One! ? Is num casted to a size_t in the switch statement? num转换为switch语句中的size_t Is this behavior defined? 是否定义了此行为?

From the C standard on switch: 从交换机的C标准:

6.8.4.2 The switch statement 6.8.4.2 switch语句
... ...
Semantics 语义
... ...
5 The integer promotions are performed on the controlling expression. 5对控制表达式执行整数提升。 The constant expression in each case label is converted to the promoted type of the controlling expression. 每个case标签中的常量表达式将转换为控制表达式的提升类型。 If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label. 如果转换后的值与提升的控制表达式的值匹配,则控制将跳转到匹配的案例标签后面的语句。

size_t is also an unsigned type per the standard (6.5.3.4 The sizeof operator, Semantics, 4). size_t也是标准的无符号类型(6.5.3.4 sizeof运算符,Semantics,4)。

So, your -1 is converted to size_t in both size_t num = -1; 所以,你的-1size_t num = -1;中都被转换为size_t size_t num = -1; and case -1: . case -1: . No wonder that (size_t)-1==(size_t)-1 evaluates to true. 难怪(size_t)-1==(size_t)-1计算结果为true。

Yes, this behavior is defined. 是的,这个行为是定义的。 The values are cast to size_t as you'd expect. 这些值会按照您的预期转换为size_t From C99 §6.8.4.2/5: 从C99§6.8.4.2/ 5:

The integer promotions are performed on the controlling expression. 对控制表达式执行整数提升。 The constant expression in each case label is converted to the promoted type of the controlling expression. 每个case标签中的常量表达式将转换为控制表达式的提升类型。 If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label. 如果转换后的值与提升的控制表达式的值匹配,则控制将跳转到匹配的case标签后面的语句。

The "controlling expression" is the expression appearing inside the parentheses after the switch keyword, ie num in this case. “控制表达式”是在switch关键字后出现在括号内的表达式,即在这种情况下为num

So, the -1 in the case label is converted to size_t (the promoted type of num ). 因此,case标签中的-1将转换为size_tnum的提升类型)。 Since the value of num is just that, the code in that case statement is executed. 由于num的值就是那个,所以执行该case语句中的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM