C语言:整型提升。

定义:

C的整型算术运算总是至少以缺省整型类型的精度来进行的。
为了获得这个精度,表达式中那些小于整型操作数的:(字符和短整型操作数)在使用之前被转换为普通整型,这种转换称为整型提升。

例子1:

#include <stdio.h>
#include <stdlib.h>
int main() {
    
    
	char a = 3;
	//因为char不满4Bety,要进行整型提升。因为char是有符号的char 提升时补最高位0.
	//3的补码为   00000000 00000000 00000000 00000011
	//00000011 存入a中。
	char b = 127;
	//因为char不满4Bety,要进行整型提升。因为char是有符号的char 提升时补最高位0.
	//127的补码为 00000000 00000000 00000000 01111111
	//01111111 存入b中。
	char c = a + b;
	//  00000000 00000000 00000000 00000011
	// +00000000 00000000 00000000 01111111
	// -------------------------------------
	//  00000000 00000000 00000000 10000010
	// 10000010 存入c中,再进行整型提升:补最高位1.
	//  11111111 11111111 11111111 10000010//c的补码
	//  11111111 11111111 11111111 10000001//c的反码
	//  10000000 00000000 00000000 01111110//c的原码==  -126
	printf("%d", c);//-126
}

例子2:

#include <stdio.h>

int main() {
    
    
	char a = 0xb6;
	//a- 10110110
	short b = 0xb600;
	//b- 10110110 00000000
	int c = 0xb6000000;
	//c- 10110110 00000000 00000000 00000000
	if (a == 0xb6)
		//a 整型提升:11111111 11111111 11111111 10110110 不等于 0xb6
		printf("a");//不打印
	if (b == 0xb600)
		//b 整型提升:11111111 11111111 10110110 00000000 不等于 0xb6
		printf("b");//不打印
	if (c == 0xb6000000)//c不用提升,二者直接就相等
		printf("c");//打印
	return 0;
}

例子3:

#include <stdio.h>

int main()
{
    
    
	char c = 1;
	//c- 00000001
	printf("%u\n", sizeof(c));//打印1
	printf("%u\n", sizeof(+c));//c整型提升00000000 00000000 00000000 00000001 打印4
	printf("%u\n", sizeof(!c));//打印1
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45275802/article/details/112568976