C 标准中 switch 语句的用语

发布于 2024-12-14 21:17:32 字数 853 浏览 1 评论 0原文

考虑以下代码示例:

char c = 0xff;
char mask = 0xfe;
switch ((unsigned)(c & mask)) {
case -2: /* do task 1 */ break;
default:   /* do task 2 */
}

让我们假设 CHAR_BIT = 8,并且实现定义的对 c 和掩码的分配是通过位模式的解释:11111111 和 11111110,并且允许负零。因此,此代码的行为是:

如果 char 有符号且实现使用 2 的补码,则 c = -1, mask = -2, c &掩码 = -2,(无符号)(c 和掩码)= UINT_MAX - 1。

如果 char 有符号且实现使用 1 的补码,则 c = 0, mask = -1, c &掩码 = 0,(无符号)(c 和掩码)= 0。 c 为零且不是负零,因为 C 不允许通过赋值创建负零。

如果 char 有符号且实现使用有符号大小,则 c = -127,掩码 = -126,c & mask = -126, (unsigned)(c & mask) = UINT_MAX - 125

如果 char 是无符号的 c = 255, mask = 254, c & mask = 254, (unsigned)(c & mask) = 254

case 常量 -2 转换为与控制表达式相同的类型,因此值为 UINT_MAX - 1。因此,仅当 char 有符号且实现使用 2 的补码时,它才会匹配。

根据 C 标准,这是否正确,或者是否需要添加其他假设?

Consider this code example:

char c = 0xff;
char mask = 0xfe;
switch ((unsigned)(c & mask)) {
case -2: /* do task 1 */ break;
default:   /* do task 2 */
}

Let us assume that CHAR_BIT = 8 and the implementation defined assignment to c and mask is via interpretation of the bit patterns: 11111111 and 11111110, and negative zeros are allowed. The behaviour of this code is therefore:

if char is signed and implementation uses 2's complement, c = -1, mask = -2, c & mask = -2, (unsigned)(c & mask) = UINT_MAX - 1.

if char is signed and implementation uses 1's complement, c = 0, mask = -1, c & mask = 0, (unsigned)(c & mask) = 0.
c is zero and not negative zero because C does not allow creation of negative zero via an assignment.

if char is signed and implementation uses signed magnitude, c = -127, mask = -126, c & mask = -126, (unsigned)(c & mask) = UINT_MAX - 125

if char is unsigned c = 255, mask = 254, c & mask = 254, (unsigned)(c & mask) = 254

The case constant -2 is converted to the same type as the controlling expression, so the value is UINT_MAX - 1. Hence it would only match if char is signed and implementation uses 2's complement.

Is this correct according to the C standard or are there additional assumptions that needs to be added?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒浓于脸红 2024-12-21 21:17:32

根据 C 标准,这是否正确

不正确。如果 char 有符号且为 8 位(即 CHAR_MAX 小于 255),则该行

char c = 0xff;

是实现定义的。它可能会按照你说的做,但也可能不会。

C标准6.3.1.3:

否则,新类型是有符号的,并且该值无法在其中表示;要么
结果是实现定义的或引发实现定义的信号。

Is this correct according to the C standard

Not really. If char is signed and 8-bit (ie. CHAR_MAX is less than 255), then the line

char c = 0xff;

is implementation-defined. It might do what you say, but it might not.

The C standard 6.3.1.3:

Otherwise, the new type is signed and the value cannot be represented in it; either the
result is implementation-defined or an implementation-defined signal is raised.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文