”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > C++ 中的“char”、“signed char”和“unsigned char”真的不同吗?

C++ 中的“char”、“signed char”和“unsigned char”真的不同吗?

发布于2024-11-05
浏览:733

  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