C/C++ 整型提升(Integral Promotion)
前言:
先確認一個事實前提,我們知道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';
https://blog.csdn.net/zhangxiao93/article/details/43989409
總結
以上是生活随笔為你收集整理的C/C++ 整型提升(Integral Promotion)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言优先级——取反和移位
- 下一篇: ubuntu9.10配置编译xawtv-