C 标准中 switch 语句的用语
考虑以下代码示例:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不正确。如果
char
有符号且为 8 位(即CHAR_MAX
小于 255),则该行是实现定义的。它可能会按照你说的做,但也可能不会。
C标准6.3.1.3:
Not really. If
char
is signed and 8-bit (ie.CHAR_MAX
is less than 255), then the lineis implementation-defined. It might do what you say, but it might not.
The C standard 6.3.1.3: