关于C/C++的整型提升

C++在进行运算操作时的整型提升问题,记录一下。

整型提升(Integral Promotion):

K&R C中关于整型提升(integral promotion)的定义为:


"A character, a short integer, or an integer bit-field, all either signed or not, or an object of enumeration type, may be used in an expression wherever an integer maybe used. If an int can represent all the values of the original type, then the value is converted to int; otherwise the value is converted to unsigned int. This process is called integral promotion."

“如果char、short int或者int型位字段(bit-field),包括它们有符号或无符号变型,以及枚举类型,可以使用在需要int或者unsigned int的表达式中。如果int可以完整表示源类型的所有值,那么该源类型的值就转换为int,否则转换为unsigned int。这称为整型提升

根据32位计算机操作系统,被转换成的int为int32 or unsigned int32。


参考if9600的关于整型提升的例子,并作出进一步的说明

int main()
{
	char c;	                        //char在表示整数时范围为-128到127
	unsigned char uc;               //unsigned char的表示范围则是0到255
	unsigned short us;
	c = 128;                        //使用时整型提升为 int32 0xffffff80 *①
	uc = 128;                       //使用时整型提升为 unsigned int32 0x00000080
	us = c + uc;                    // 0xffffff80 + 0x00000080 = 0x100000000 
	printf("0x%x\n", us);
	us = (unsigned char)c + uc;     // 0x00000080 + 0x00000080 = 0x00000100
	printf("0x%x\n", us);
	us = c + (char)uc;              // 0xffffff80 + 0xffffff80 = 0x1ffffff00
	printf("0x%x\n", us);

	system("pause");
	return 0;
}                                       //结果:0x0 0x100 0xff00

*①、c++类型转换时的符号位扩展

原因是,通常情况下,在对int类型的数值作运算时,CPU的运算速度是最快的。在x86上,32位算术运算的速度比16位算术运算的速度快一倍,C语言是一个注重效率的语言,所以它会作整型提升,使得程序的运行速度尽可能地快。

可以把整型提升理解为把C语言类型直接映射到机器指令的一种机制。所有算术操作的操作数被转成有符号或无符号int后,都会被当作一个小的int的计算。(windmissingC语言进阶:整型提升


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值