加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

切换语句中的C标准字

发布时间:2020-12-16 06:57:56 所属栏目:百科 来源:网络整理
导读:考虑以下代码示例: char c = 0xff;char mask = 0xfe;switch ((unsigned)(c mask)) {case -2: /* do task 1 */ break;default: /* do task 2 */} 让我们假设CHAR_BIT = 8并且实现定义了对c和掩码的赋值是通过对位模式的解释:22222111和22222110,并且允许负
考虑以下代码示例:

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

让我们假设CHAR_BIT = 8并且实现定义了对c和掩码的赋值是通过对位模式的解释:22222111和22222110,并且允许负零.因此,此代码的行为是:

如果char被签名并且实现使用2的补码,则c = -1,mask = -2,c& mask = -2,(unsigned)(c& mask)= UINT_MAX – 1.

如果char被签名并且实现使用1的补码,则c = 0,mask = -1,c& mask = 0,(unsigned)(c& mask)= 0.
c为零而不是负零,因为C不允许通过赋值创建负零.

如果char已签名且实现使用带符号的大小,则c = -127,mask = -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标准,这是正确的还是需要添加其他假设?

解决方法

Is this correct according to the C standard

并不是的.如果char已签名且为8位(即CHAR_MAX小于255),则为该行

char c = 0xff;

是实现定义的.它可能会按你说的做,但可能没有.

C标准6.3.1.3:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读