如有错误请留言告知,谢谢!
C语言中整型提升的概念:
If an int canrepresent all the values of the original type, then the value is converted toint; otherwise the value is converted to unsigned int. This process is calledintegral promotion。
假如原始类型可以用int来表示,那么原始值会被转换为int,否则转换为unsigned int。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char a,b;
a = 'A';
b = 'B';
printf("sizeof(a)=%d, sizeof(b)=%d\n",sizeof(a),sizeof(b));
printf("sizeof('A')%d\n",sizeof('A'));
printf("sizeof(a+b)=%d\n",sizeof(a+b));
system("PAUSE");
return 0;
}
![](http://hi.csdn.net/attachment/201201/11/0_1326291967b6z5.gif)
1.a,b本身类型为char
2.在C语言中,'A'本身就是int型(但不同的编译器计算出的结果差异非常大,用VC++6.0的时候输出sizeof('A')输出1,换DEV-C++,创建的C工程sizeof('A')的结果为4!。应该和创建工程时采取的默认编译标准不一样有关)
3.四则运算前,各个比int窄的加数自动提升为int,结果也为int类型,故size为4,sizeof只是确定表达式的存储长度,并不对值进行计算。
另外贴一个网上流传的,和整型提升有关的题目:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
unsigned char a = 0xA5;
unsigned char b = ~a>>4+1;
printf("b=%d\n",b);
system("PAUSE");
return 0;
}
![](http://hi.csdn.net/attachment/201201/11/0_13262925930Rrg.gif)
博主自己思考后的一个例子:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
unsigned char a,b;
unsigned char c;
a = 255;
b = 2;
c = a + b;
printf("output a+b = %d\n",(a+b));
printf("output c = %d\n",c);
system("PAUSE");
return 0;
}
![](https://img-my.csdn.net/uploads/201204/23/1335166203_5399.jpg)
从这个结果可以判断出,unsigneg char类型的a、b,在代入表达式a+b计算的时候是自动被转换为int型来计算的。
这可以由控制输出%d,以及a+b的输出结果257来推断。因为%d的作用就是用来控制a+b的结果按照整型的格式来
输出,但是其输出的类型由后面的表达式类型来决定的。因为同样的两个%d,unsigned char c的输出结果就只能
输内存中的8bit,但是a+b提升到int后占用了32bit,所以输出结果就有上述不同了。