4

我写了这段代码:

#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 更多的内存时?反之亦然?标准是什么?

4

4 回答 4

2

Why have the long if there will be instances of machines that make no use of its abilities?因为有些机器利用它的能力。

于 2013-07-10T19:28:41.563 回答
2

如果您愿意的话,是否有“经验法则”,因为当机器的编译器会选择在 long 上分配比 int 更多的内存时?反之亦然?标准是什么?

标准可能是“目标机器会利用更大的类型吗?” 或“目标机器是否具有在这种更大类型上运行的本机寄存器和/或指令?”

于 2013-07-10T19:34:40.857 回答
0

“int”至少为 16 位,“long int”至少为 32 位。

“int”可以容纳高达 32,767 的值,“long int”可以容纳高达 2,147,483,647 的值。

limits.h头文件中,您可以找到相应机器的最大值和最小值。

于 2013-07-10T21:19:59.833 回答
-1

在 32 位和更高位的机器上,long 的大小等于 int 的大小,即 32 位。在 16 位机器上,short 的大小等于 int 的大小,即 16 位,而 long 的大小是 32 位。所以在 16 位机器上 long 是 32 位,它比 short 和 bit 可以容纳更大的范围。

于 2013-07-10T20:26:06.410 回答