C语言中的整型提升(integral promotion)
2013-08-24 19:47
337 查看
文章转自:http://wangwenbingood1988.blog.163.com/blog/static/3515459320116305111598/
记得自己以前写过一篇有关整形提升的文章,今天在面试宝典上又遇到这么一道题
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了
记得自己以前写过一篇有关整形提升的文章,今天在面试宝典上又遇到这么一道题
#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了
相关文章推荐
- C语言中的整型提升(integral promotion)
- C语言进阶:整型提升
- C语言中的数值类型转换:整型提升/寻常算术变化/截断/强制类型转换
- C语言进阶:整型提升
- C语言中的整型提升(integral promotion)
- c语言 无符号数 结构体指针 整型提升
- C语言中的整型提升与混合类型数据的运算
- 7_24日C语言|整型提升相关介绍
- C语言中的整型提升与混合类型数据的运算
- 【C语言】整型溢出和整型提升
- 关于C语言整型提升的讲解
- C语言 sizeof 整型提升 类型转换
- C语言中的整型提升(Integral Promotion)
- c语言 整型 字符 字符串之间的转换
- C语言中长短整型数据之间的相互转换及运算-其实很简单
- 【C语言常用技巧】字符串整型转换
- C语言长整型相乘
- C语言printf函数格式化打印之长整型
- C语言基本数据类型:整型(int)用法详解
- c语言 字符与整型之间的关系