gpt4 book ai didi

c - 为 size_t 切换为负值

转载 作者:行者123 更新时间:2023-12-04 11:30:42 26 4
gpt4 key购买 nike

如果我有以下片段:

size_t num = -1;

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

为什么程序打印Minus One!num 是否在 switch 语句中转换为 size_t?这种行为是否已定义?

最佳答案

来自 switch 的 C 标准:

6.8.4.2 The switch statement
...
Semantics
...
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. If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label.

size_t 也是符合标准的无符号类型(6.5.3.4 The sizeof operator, Semantics, 4)。

因此,您的 -1size_t num = -1;case -1 中都被转换为 size_t:。难怪 (size_t)-1==(size_t)-1 的计算结果为真。

关于c - 为 size_t 切换为负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7720663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com