我写了这段代码:
#include <stdio.h>
int main(){
printf("Size of short int: %d \n", sizeof(short));
printf("Size of int: %d \n", sizeof(int));
printf("Size of long int: %d \n", sizeof(long));
printf("Size of float: %d \n", sizeof(float));
printf("Size of double: %d \n", sizeof(double));
printf("Size of long double: %d \n", sizeof(long double));
return 0;
}
输出在哪里:
Size of short int: 2
Size of int: 4
Size of long int: 4
Size of float: 4
Size of double: 8
Size of long double: 12
自然,整数和浮点数据类型之间存在差异,但是任何编译器将相同数量的内存分配给 long 和 int 的原因是什么?long 旨在处理更大的值,但如果像上面那样完成(对于整数的情况),它就没有用了。浮点长变量增加了额外的 16 位分配。
那么,我的问题本质上是,如果会有不使用其能力的机器实例,为什么还要长久?
来自 K&R 电子书:
The intent is that short and long should provide different lengths of integers where practical; int will
normally be the natural size for a particular machine. short is often 16 bits long, and int either 16 or
32 bits. Each compiler is free to choose appropriate sizes for its own hardware, subject only to the the
restriction that shorts and ints are at least 16 bits, longs are at least 32 bits, and short is no longer
than int, which is no longer than long.
如果您愿意的话,是否有“经验法则”,因为当机器的编译器会选择在 long 上分配比 int 更多的内存时?反之亦然?标准是什么?