整型升级:
字符和整型,包括无符号和有符号的char,short int 和 int,以及枚举类型,
当两个类型运算时,如果int可以表示源类型的值,就转换成int,不行就转换成unsigned int。
举个列子:
#include
char a0;
int a2;
unsigned char b0;
short int a1;
unsigned int b1;
main()
{
printf("sizeof(char)=%d\n",sizeof(a0));
printf("sizeof(unsigned char)=%d\n",sizeof(b0));
printf("sizeof(short int)=%d\n",sizeof(a1));
printf("sizeof(int)=%d\n",sizeof(a2));
printf("sizeof(unsigned int)=%d\n",sizeof(b1));
printf("sizeof(char+unsigned char)=%d\n",sizeof(a0+b0));
printf("sizeof(char+int)=%d\n",sizeof(a0+a2));
}
运行结果:
sizeof(char)=1
sizeof(unsigned char)=1
sizeof(short int)=2
sizeof(int)=4
sizeof(unsigned int)=4
sizeof(char+unsigned char)=4
sizeof(char+int)=4
结果sizeof(char)=1,sizeof(unsigned char)=1,char和unsigned char均为一个字节,但sizeof(char+unsigned char)=4,运算时变成四个字节,说明运算时进行了整形升级。
寻常算速转换
如果一个是long double,另一个也转换成long double;如果一个是double,另一个也转换成 double;如果一个是float,另一个也转换成float;否则进行上面的整型升级,执行下面规则:
如果一个是unsigned long int,另一个也转换成unsigned long int。如果一个是long int,另一个是unsigned int。如果long int可以表示源类型的所有值,unsigned int就转换成long int,如果不能,那么两个都转换unsigned long int;如果一个是long int,另一个也转换成 long int。如果一个是unsigned int,另一个也转换成unsigned int。
如果都不属于,两个都为int 。
测试一下:
#include
int a0;
long double a1;
double a2;
float a3;
unsigned long int a4;
long int a5;
unsigned int a6;
main()
{
printf("sizeof(int)=%d\n",sizeof(a0));
printf("sizeof(long double)=%d\n",sizeof(a1));
printf("sizeof(double)=%d\n",sizeof(a2));
printf("sizeof(float)=%d\n",sizeof(a3));
printf("sizeof(unsigned long int)=%d\n",sizeof(a4));
printf("sizeof(long int)=%d\n",sizeof(a5));
printf("sizeof(unsigned int)=%d\n",sizeof(a6));
printf("\n\n\n");
printf("sizeof(long double+int)=%d\n",sizeof(a1+a0));
printf("sizeof(double+int)=%d\n",sizeof(a2+a0));
printf("sizeof(float+int)=%d\n",sizeof(a3+a0));
printf("sizeof(unsigned long int+int)=%d\n",sizeof(a4+a0));
printf("sizeof(long int+unsigned int)=%d\n",sizeof(a5+a6));
printf("sizeof(long int+int)=%d\n",sizeof(a5+a0));
printf("sizeof(unsigned int+int)=%d\n",sizeof(a6+a0));
}
运行结果:
sizeof(int)=4
sizeof(long double)=16
sizeof(double)=8
sizeof(float)=4
sizeof(unsigned long int)=8
sizeof(long int)=8
sizeof(unsigned int)=4
sizeof(long double+int)=16
sizeof(double+int)=8
sizeof(float+int)=4
sizeof(unsigned long int+int)=8
sizeof(long int+unsigned int)=8
sizeof(long int+int)=8
sizeof(unsigned int+int)=4
对比测试结果,印证了上面结论。
算术转换与bug:
稍不注意,没有遵循上面的规则,就会产生一个bug,并且比较难发现;
如:
1.如果一个是unsigned int,另一个也转换成unsigned int
#include
int a=-1;
unsigned int b=1;
int main()
{
if(a>=b)
printf("a>=b\n");
else
printf("a
return 0;
}
测试结果:
a>=b
结果表明,在a>=b这个运算中,a被转换unsigned int,是个很大的数,所以会出现错误。
解决这个bug,只要把unsigned int强制转换成int,当然int要装得下b。
如
#include
int a=-1;
unsigned int b=1;
int main()
{
if(a>=(int)b)
printf("a>=b\n");
else
printf("a
return 0;
}
结果a
对于使用建议,参见下面图片的小启发,来自《c专家编程》
上述结论摘自《c专家编程》
阅读(1954) | 评论(0) | 转发(0) |