c/c++整型提升/类型提升

Posted 上下求索.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c/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."

关于整型提升,ANSI C 有如下说明:

  在执行下列代码段时

  char c1,c2;

  /* ··· */

  c1 = c1 + c2;

  “整型提升”规则要求抽象机器把每个变量的值提升为 int 的长度,然后对两个 int 值执行加法运算,然后再

对运算结果进行裁剪。如果两个 char 的加法运算结果不会发生溢出异常,那么在实际执行时只需要产生 char

类型的元算结果,可以省略类型提升。

  类似,在下列代码段中

  float f1,f2;

  double d;

  /* ··· */

  f1 = f2 * d;

  如果编译器可以确定用 float 进行运算的结果跟转换为 double 后进行运算(例如,d 由类型为 double

的常量 2.0 所代替)的结果一样,那么也可以使用 float 来进行乘法运算。

                                           ——ANSI C 标准,第5.1.2.3节

C语言中的类型提升
源类型通常提升后的类型
charint
位段(bit - field)int
枚举(enum)int
unsigned charint
shortint
unsigned shortint
floatdouble
任何数组相应类型的指针

  整型提升就是 char、short int 和位段类型(无论 signed 或 unsigned)以及枚举类型将被提升

为 int ,前提是 int 能够完整的容纳原先的数据,否则将被转换为 unsigned int 。ANSI C 表示如果

编译器能够保证运算结果一致,也可以省略类型提升——这通常出现在表达式中存在常量操作数的时候。

这就很容易解释:

char c;

printf ("c:0x%x\\n", c);

得到结果0xffffffff

把char类型强制转换为unsigned char (uint8_t)类型,使用unsigned char (uint8_t)时,是无符号提升,前面的填充为0,所以提升后的值为0xFF

以上是关于c/c++整型提升/类型提升的主要内容,如果未能解决你的问题,请参考以下文章

C语言学习--代码分析整形提升过程

隐式类型转换和整型提升

C语言 - 隐式类型转换

C语言整型提升

C语言中的整型提升

C语言中的整型提升