首頁 > 後端開發 > C++ > 主體

C 中的「char」、「signed char」和「unsigned char」真的不一樣嗎?

Linda Hamilton
發布: 2024-10-26 04:22:31
原創
420 人瀏覽過

  Are `char`, `signed char`, and `unsigned char` Truly Distinct in C  ?

C 中的字元類型:不同還是等效?

在 C 中,字元類型 (char) 的行為有時可能與有符號和無符號整數,導致混亂。具體來說,以下程式碼示範了這種差異:

<code class="cpp">#include <iostream>

typedef   signed char       int8;
typedef unsigned char      uint8;

struct TrueType {};
struct FalseType {};

template <typename T>
struct isX
{
   typedef typename T::ikIsX ikIsX;
};

template <>            struct isX<char  >  { typedef FalseType ikIsX; };
template <>            struct isX<int8  >  { typedef FalseType ikIsX; };
template <>            struct isX<uint8 >  { typedef FalseType ikIsX; };

template <typename T> bool getIsTrue();
template <>           bool getIsTrue<TrueType>() { return true; }
template <>           bool getIsTrue<FalseType>() { return false; }

int main(int, char **t )
{
   cout << getIsTrue< isX<char>::ikIsX  >() << endl;
   cout << getIsTrue< isX<int8>::ikIsX  >() << endl;
   cout << getIsTrue< isX<uint8>::ikIsX  >() << endl;
}</code>
登入後複製

此程式碼可以編譯,但為 char 產生的結果與 int8 和 uint8 不同。這是因為 C 將 char、signed char 和 unsigned char 視為三種不同的類型。

相反,int 和 uint32 是等效的類型:

<code class="cpp">template <>            struct isX<int   >  { typedef FalseType ikIsX; };
template <>            struct isX<unit32>  { typedef FalseType ikIsX; };</code>
登入後複製

這種區別源於以下事實: char 歷史上曾用於表示字符和存儲數值。因此,C 透過將普通 char 視為與 int 不同的單獨類型來保持向後相容性。

要確定 char 使用兩種表示中的哪一種,實現定義的 typedef char_traits::signed 是假如。如果這是 true,則 char 表現為有符號類型;否則,它表現為無符號類型。

以上是C 中的「char」、「signed char」和「unsigned char」真的不一樣嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!