且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么某些编译器的int大小有所不同?

更新时间:2023-11-10 16:17:04

虽然为什么可以回答因为标准如此说,人们可以提出这样的论点,即标准可以用不同的方式编写,以保证特定的尺寸。

Whilst the "why" can be answered with "Because the standard says so", one could make the argument that the standard could be written differently, to guarantee a particular size.

然而,C和C ++的目的是在所有机器上生成非常快的代码。如果编译器必须确保 int 对于该机器是不自然的大小,则需要额外的指令。对于几乎所有情况,这都不是必需的,你所关心的只是它足够大到我想做的事情。因此,为了给编译器提供生成良好代码的良好机会,该标准仅指定最小大小,避免编译器必须生成额外代码以使 int (和其他类型)以非常特定的方式表现。

However, the purpose of C and C++ is to produce very fast code on all machines. If the compiler had to make sure that an int is a "unnatural size" for that machine, it would require extra instructions. For nearly all circumstances, that is not required, all you'd care about is that it's "big enough for what I want to do". So, to give the compiler a good chance to generate "good code", the standard specifies only minimum sizes, avoiding the compiler having to generate "extra code" to make int (and other types) behave in a very specific way.

C和C ++的众多优点之一是有针对各种机器的编译器,从小型8位和16位微控制器到大型机器,64像PC中那样的多核处理器。当然,还有一些18,24或36位的机器。如果您的机器具有36位原生大小,如果由于某些标准的说法,您会因为额外的指令而在整数数学中获得一半的性能,并且不能使用前4位 int ...

One of the many benefits of C and C++ is that there are compilers to target a vast range of machines, from little 8- and 16-bit microcontrollers to large, 64-bit multi-core processors like the ones in a PC. And of course, some 18, 24 or 36-bit machines too. If your machine has a 36-bit native size, you wouldn't be very happy if, because some standard says so, you get half the performance in integer math due to extra instructions, and can't use the top 4 bits of an int...

具有8位寄存器的小型微处理器通常支持进行16位加法和减法(也许还有乘法和除法),但32位数学会涉及将这些指令加倍[以及乘法和除法的更多工作]。所以16位整数(2字节)在这么小的处理器上会更有意义 - 特别是因为内存可能也不是很大,所以为每个整数存储4个字节有点浪费。在32位或64位机器中,内存范围很可能要大得多,因此具有较大的整数并不是一个缺点,32位整数运算与较小的整数运算速度相同(在某些情况下) 更好 - 例如在x86中,16位简单的数学运算(如加法或减法)需要额外的前缀字节来表示使这个16位,因此16位整数的数学会占用更多的代码空间)。

A small microprocessor with 8-bit registers often have support to do 16-bit additions and subtractions (and perhaps also multiplication and divide), but 32-bit math would involve doubling up on those instructions [and more work for multiplication and divide]. So 16-bit integers (2 byte) would make much more sense on such a small processor - particularly since memory is probably not very large either, so storing 4 bytes for every integer is a bit of a waste. In a 32- or 64-bit machine, memory range is most likely a lot larger, so having larger integers isn't that much of a drawback, and 32-bit integer operations are the same speed as smaller ones (and in some cases "better" - for example in x86, a 16-bit simple math operation such as addition or subtraction requires an extra prefix byte to say "make this 16-bit", so math on 16-bit integers would take up more code-space).