您的位置:首页 > 编程语言 > C语言/C++

C语言中的整型提升(integral promotion)

2013-08-24 19:47 337 查看
文章转自:http://wangwenbingood1988.blog.163.com/blog/static/3515459320116305111598/

记得自己以前写过一篇有关整形提升的文章,今天在面试宝典上又遇到这么一道题

#include<iostream>
using namespace std;

int main()
{
unsigned char a = 0xa5;
unsigned char b = ~a>>4+1;

printf("b=%d\n",b);
return 0;
}


A.245 B.246 C.250 D.2;

答案:C。

可以参考下面这篇文章:

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."

上面的定义归纳下来就是以下两个原则:
1). 只要一个表达式中用到了整型值,那么类型为char、short int活整型位域(这几者带符号或无符号均可)的变量,以及枚举类型的对象,都可以被放在这个整型变量的位置。
2). 如果1)中的变量的原始类型值域可以被int表示,那么原值被转换为int;否则的话,转为unsigned int。

以上两者作为一个整体,被成为整型提升(Integral promotion)
整型提升的概念容易与普通算术类型转换产生混淆。这两者的区别之一在于后者是在操作数之间类型不一致的情况下发生,最终将操作数转换为同一类型。而在算术运算这种情景下,即使操作数具有相同的类型,仍有可能发生整型提升。
例如:

char a , b ,c;
c=a + b;

在上述过程中,尽管两个运算符"+"和"="的操作数全为char型,但在中间计算过程中存在着整数提升:对于表达式a+b ,a、b都是char型,因此被提升至int型后,执行“+”运算,计算结果(int型)再赋值给c(char型),又执行了隐式的类型转换。

看完这个转载的文章,我也简单的试了一下:

char a='A',b='B',c;
c=a+b;
printf ( " the size of the result of a+b :%d " ,sizeof(a+b) );

这个输出的结果是4,和上面所说的的确是一样的,但是如果sizeof(c)就是1了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: