C/C++ 整型提升(Integral Promotion)

来源:互联网 发布:创意礼品 知乎 编辑:程序博客网 时间:2024/06/01 10:30

前言:

先确认一个事实前提,我们知道C/C++中的char字符都有它对应的ASCII码(一般情况下0~127),那么对于一个char变量输出它的ASCII码则需要 int显示转换。

例如:

<span style="font-family:Microsoft YaHei;font-size:12px;">char c = 'a';cout << c << endl;cout << (int)c << endl;//输出:// a//97</span>


整型提升(Integral Promotion):

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

大概意思是所谓的char、short 等类型在表达式中按照int 或者 unsigned int 进行计算。事实上由于做嵌入式的经历,在我个人的理解为,不涉及浮点的表达式或者变量,

即在一般的32位系统中整型(int)和无符号整型(unsigned int) 都是4字节32位,而char/unsigned char 为1个字节8位,short为2个字节16位在进行表达式计算时,在前面补0对齐32位,

这就成了 “整型”。

下面看测试代码

demo1:

#include <iostream>using namespace std;int main(int argc , char * argv[]){char ch1='a';char ch2='b';char ch;cout <<"sizeof('a') = " << sizeof('a') << endl;cout <<"sizeof(ch1) = " << sizeof(ch1) << endl; cout <<"sizeof(ch = ch1 + ch2) = " << sizeof(ch=(ch1+ch2)) << endl;cout <<"sizeof(ch1 + ch2) = " << sizeof( ch1 + ch2) << endl;return 0;}//输出://1//1//1//4

结果不难理解,只需要注意整型提升发生的时机是在表达式中,分析第3个与第4个输出,不难得出以下的逻辑:

计算时(表达式中),将变量进行整型提升(第四种情况),而又由于ch是char型,在赋值过程中又进行了一个类型的隐式变换(int ->char),即第三种情况。

如果你仍然迷惑,那么你应该愿意将上述代码的char ch; 改为 int ch;    或者再看下面的测试代码:

demo2:

#include <iostream>using namespace std;int main(int argc, char* argv[]){char ch1= 'a';cout << "++ch1 = " << ++ ch1 << endl; cout << "ch1+1 = "<< ch1 + 1  << endl;return 0;}//输出://b//99

同样是 “+1”,第一个前导++ 逻辑为: ch1 = ch1 + 1;  表达式计算后再进行赋值,注意由于ch1 是char型,再整型提升过后的赋值过程有一个类型隐式转化的过程。

而第二个仅仅只是表达式,整型提升后强制转换为int型后输出当然是ASCII码了。同样你依然愿意尝试将上述例子中char ch1 = 'a'; 改为int ch1 = 'a';












0 0
原创粉丝点击