C/C++ 整型提升(Integral Promotion)
前言:
先確認(rèn)一個事實(shí)前提,我們知道C/C++中的char字符都有它對應(yīng)的ASCII碼(一般情況下0~127),那么對于一個char變量輸出它的ASCII碼則需要 int顯示轉(zhuǎn)換。
例如:
<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中關(guān)于整型提升(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 等類型在表達(dá)式中按照int 或者 unsigned int 進(jìn)行計算。事實(shí)上由于做嵌入式的經(jīng)歷,在我個人的理解為,不涉及浮點(diǎn)的表達(dá)式或者變量,
即在一般的32位系統(tǒng)中整型(int)和無符號整型(unsigned int) 都是4字節(jié)32位,而char/unsigned char 為1個字節(jié)8位,short為2個字節(jié)16位在進(jìn)行表達(dá)式計算時,在前面補(bǔ)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
結(jié)果不難理解,只需要注意整型提升發(fā)生的時機(jī)是在表達(dá)式中,分析第3個與第4個輸出,不難得出以下的邏輯:
計算時(表達(dá)式中),將變量進(jìn)行整型提升(第四種情況),而又由于ch是char型,在賦值過程中又進(jìn)行了一個類型的隱式變換(int ->char),即第三種情況。
如果你仍然迷惑,那么你應(yīng)該愿意將上述代碼的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”,第一個前導(dǎo)++ 邏輯為: ch1 = ch1 + 1; ?表達(dá)式計算后再進(jìn)行賦值,注意由于ch1 是char型,再整型提升過后的賦值過程有一個類型隱式轉(zhuǎn)化的過程。
而第二個僅僅只是表達(dá)式,整型提升后強(qiáng)制轉(zhuǎn)換為int型后輸出當(dāng)然是ASCII碼了。同樣你依然愿意嘗試將上述例子中char ch1 = 'a'; 改為int ch1 = 'a';
https://blog.csdn.net/zhangxiao93/article/details/43989409
總結(jié)
以上是生活随笔為你收集整理的C/C++ 整型提升(Integral Promotion)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言优先级——取反和移位
- 下一篇: 图像配准代码(包含matlab/open