」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > C++ 中的「char」、「signed char」和「unsigned char」真的不一樣嗎?

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

發佈於2024-11-05
瀏覽:333

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

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

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

#include 

typedef   signed char       int8;
typedef unsigned char      uint8;

struct TrueType {};
struct FalseType {};

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

template             struct isX  { typedef FalseType ikIsX; };
template             struct isX  { typedef FalseType ikIsX; };
template             struct isX  { typedef FalseType ikIsX; };

template  bool getIsTrue();
template            bool getIsTrue() { return true; }
template            bool getIsTrue() { return false; }

int main(int, char **t )
{
   cout ::ikIsX  >() ::ikIsX  >() ::ikIsX  >() 

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

相反,int 和 uint32 是等價型別:

template             struct isX  { typedef FalseType ikIsX; };
template             struct isX  { typedef FalseType ikIsX; };

這種差異源自於這樣一個事實:char 歷來被用來表示字元和儲存數值。因此,C 透過將普通 char 視為與 int 不同的單獨類型來保持向後相容性。

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

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3