日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

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

發(fā)布時間:2025/4/5 c/c++ 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C/C++ 整型提升(Integral Promotion) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

前言:

先確認一個事實前提,我們知道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 等類型在表達式中按照int 或者 unsigned int 進行計算。事實上由于做嵌入式的經(jīng)歷,在我個人的理解為,不涉及浮點的表達式或者變量,

即在一般的32位系統(tǒng)中整型(int)和無符號整型(unsigned int) 都是4字節(jié)32位,而char/unsigned char 為1個字節(jié)8位,short為2個字節(jié)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
結(jié)果不難理解,只需要注意整型提升發(fā)生的時機是在表達式中,分析第3個與第4個輸出,不難得出以下的邏輯:

計算時(表達式中),將變量進行整型提升(第四種情況),而又由于ch是char型,在賦值過程中又進行了一個類型的隱式變換(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; ?表達式計算后再進行賦值,注意由于ch1 是char型,再整型提升過后的賦值過程有一個類型隱式轉(zhuǎn)化的過程。

而第二個僅僅只是表達式,整型提升后強制轉(zhuǎn)換為int型后輸出當然是ASCII碼了。同樣你依然愿意嘗試將上述例子中char ch1 = 'a'; 改為int ch1 = 'a';


https://blog.csdn.net/zhangxiao93/article/details/43989409

《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的C/C++ 整型提升(Integral Promotion)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。