整数和多头?

时间:2013-07-10 19:24:53

标签: c compiler-construction integer long-integer allocation

我写了这段代码:

#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被设计为处理更大的值,但是如果像上面那样完成则没有用(对于整数的情况)。浮点长变量增加了额外的16位分配。

那么,我的问题,实质上就是为什么如果机器的实例没有使用它的能力那么长呢?

来自K&amp; 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.

是否有“经验法则”,如果你愿意的话,因为机器的编译器会选择分配更长的内存而不是int?反之亦然?标准是什么?

4 个答案:

答案 0 :(得分:2)

Why have the long if there will be instances of machines that make no use of its abilities?因为某些机器利用其功能。

答案 1 :(得分:2)

  

是否有“经验法则”,如果你愿意的话,对于机器的编译器   会选择分配更长的内存而不是int吗?而副   反之亦然?标准是什么?

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

答案 2 :(得分:0)

&#34; INT&#34;是至少16位和&#34; long int&#34;至少是32位。

&#34; INT&#34;可以保存最多32,767和&#34; long int&#34;最高可达2,147,483,647。

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

答案 3 :(得分:-1)

在32位和更高位的机器上,long的大小等于int的大小,即32位。在16位机器上,short的大小等于int的大小,即16位,而long的大小是32位。因此在16位机器上长32位,可以保持大范围而不是短和位。