"自然大小"在C++中的真正含义是什么?

day*_*oli 6 c++ int performance short long-integer

我知道'自然大小'是特定硬件最有效处理的整数宽度.当使用short以阵列或在算术运算中,short整数必须首先被转换成int.

问:究竟什么决定了这种"自然尺寸"?

我不是在寻找简单的答案

如果它具有32位架构,则其自然大小为32位

我想了解为什么这是最有效的,而且为什么short,要在做算术运算之前转换.

奖金问:对long整数进行算术运算会发生什么?

Mar*_*k B 8

一般而言,每个计算机体系结构被设计成使得某些类型大小提供最有效的数值运算.具体大小取决于体系结构,编译器将选择合适的大小.关于为什么硬件设计者为特定硬件选择某些尺寸的更详细解释将超出stckoverflow的范围.

一个short最被晋升为int执行积分操作,因为这是它是用C的方式,和C++继承了很少或根本没有理由的行为去改变它,可能破坏现有的代码之前.我不确定它最初是在C中添加的原因,但可以推测它与"default int"相关,其中如果int编译器没有指定类型.

奖金A:从5/9(表达式)我们学习: Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

然后特别感兴趣:

  • 浮点规则在这里无关紧要
  • Otherwise, the integral promotions (4.5) shall be performed on both operands
  • Then, if either operand is unsigned long the other shall be converted to unsigned long.
  • Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.
  • Otherwise, if either operand is long, the other shall be converted to long.

总之,编译器尝试使用它可以执行二进制操作的"最佳"类型,使用的int是最小的大小.


Sne*_*tel 7

'自然大小'是特定硬件最有效处理的整数宽度.

并不是的.考虑x64架构.从8到64位的任何大小的算术将基本上是相同的速度.那么为什么所有的x64编译器都支持32位int呢?好吧,因为那里有很多代码,最初是为32位处理器编写的,而且很多代码都隐含地依赖于32位的内存.并且鉴于一种类型的近无用性可以表示高达九个数值的值,每个整数的额外四个字节实际上将是未使用的.因此,我们已经确定32位整数对于这个64位平台来说是"自然的".

比较80286架构.寄存器中只有16位.在这样的平台上执行32位整数加法基本上需要将其分成两个16位加法.用它做任何事都涉及将它分开,真的 - 以及随之而来的减速.80286的"自然整数大小"绝对不是 32位.

实际上,"自然"归结为处理效率,内存使用和程序友好等因素.这不是酸性测试.这是架构/编译器设计者的主观判断问题.