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 ::ikIsX >() ::ikIsX >() ::ikIsX >() <p>此代码可以编译,但为 char 生成的结果与 int8 和 uint8 不同。这是因为 C 将 char、signed char 和 unsigned char 视为三种不同的类型。</p> <p>相反,int 和 uint32 是等效的类型:</p> <pre class="brush:php;toolbar:false"><code class="cpp">template struct isX<int> { typedef FalseType ikIsX; }; template struct isX<unit32> { typedef FalseType ikIsX; };</unit32></int></code>
这种区别源于以下事实: char 历史上曾用于表示字符和存储数值。因此,C 通过将普通 char 视为与 int 不同的单独类型来保持向后兼容性。
要确定 char 使用两种表示中的哪一种,实现定义的 typedef char_traits
以上是C 中的'char”、'signed char”和'unsigned char”真的不同吗?的详细内容。更多信息请关注PHP中文网其他相关文章!