移位会自动将char提升为int吗? [英] Does bit shift automatically promote chars to int?

查看:121
本文介绍了移位会自动将char提升为int吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到某处按位移位会自动将操作数转换为整数.但是我不确定该语句是否应使用如果操作数的类型不相等"来限定.

I read somewhere that bitwise shift automatically turns the operand into an int. But I'm not sure if that statement should be qualified with "if the operands are of unequal type."

char one = 1, bitsInType = 8;
one << (bitsInType - one);

第二行的默认结果是int还是char?

Does the default result of the second line result in an int or char?

推荐答案

在常规C实现中,结果类型为int. 1

The result type is int in normal C implementations.1

根据C 2011(N1570)6.5.7,整数提升在每个操作数上执行.结果的类型是提升后的左操作数的类型."

Per C 2011 (N1570) 6.5.7, "The integer promotions are performed on each of the operands. The type of the result is the that of the promoted left operand."

根据6.3.1.1 2,整数提升适用于等级小于或等于 int unsigned int 的等级的整数类型的对象或表达式: 如果 int 可以代表原始类型的所有值(受位字段的宽度限制),则该值将转换为 int ;否则,它将转换为 unsigned int ."

Per 6.3.1.1 2, the integer promotions are, for objects or expressions of integer type with rank less than or equal to the rank of int and unsigned int: "If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int."

1 在Stack Overflow的其他地方进行了讨论,看来奇怪的C实现可能具有与int相同宽度的char,这导致了一些异常行为.

1There has been discussion elsewhere in Stack Overflow from which it seems that a bizarre C implementation could have a char of the same width as int, which leads to some unusual behavior.

这篇关于移位会自动将char提升为int吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆