c++ - 在 C 中,如何确定两种类型是否相同?

标签 c++ c

来自

http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc03compatible_types.htm

算术类型的各种组合中类型说明符的存在可能表示也可能不表示不同的类型。例如,signed int 类型与 int 相同,除非用作位字段的类型;但是 char、signed char 和 unsigned char 是不同的类型。

int 和 char 在类型标识方面存在差异的原因是什么?

我想同样的规则也适用于 C++。因此在这个问题中也添加了 c++ 标签

最佳答案

原来 C 没有 unsigned 类型,所以 char 默认是有符号的。由于 PDP-11 使用 8 位字节和 ASCII 字符集,char 对象是 not expected to take negative values :

Characters (declared, and hereinafter called, char) are chosen from the ASCII set; they occupy the right-most seven bits of an 8-bit byte. It is also possible to interpret chars as signed, 2’s complement 8-bit numbers.

unsigned 类型为 added around 1977部分是为了阻止对无符号算术使用指针:

[...] the similarity of the arithmetic properties of character pointers and unsigned integers made it hard to resist the temptation to identify them. The unsigned types were added to make unsigned arithmetic available without confusing it with pointer manipulation.

使 char 有符号的问题在于,为了对 char 值执行算术运算,有必要 sign-extend他们。这在具有 SXT 指令的 PDP-11 上很有效,但是 not on ARM (至少,直到 ARM 架构的第 4 版于 1996 年发布时):

[...] you'll find no single "load character from memory and sign extend" in the ARM instruction set. That's why, for performance reasons, every compiler I'm aware of makes the default char type signed on x86, but unsigned on ARM. [...]

因此,当 C 被标准化时,委员会可以选择是使 char 带符号 - 从而迫使 ARM 实现改变以变得低效 - 或者反射(reflect)现有实践并使 char 带符号 实现定义。

关于c++ - 在 C 中,如何确定两种类型是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25453665/

相关文章:

c++ - C++ 是否存在循环列表的标准实现?

c++ - 解析为 x3::variant 时出现编译器错误

C程序写最后几行程序,求错误?

c - 动态内存分配器(堆)

c - ActionScript 2.0 中有类似 C 的 #define 的东西吗?

c - 在C语言中,如何获取两个括号之间的字符串?

c++ - c++中的xml反序列化

c++ - 模板依赖 false

php - Proc_open() c++/python

c - 使用套接字程序接受顺序用户输入