Search code examples
cintegerlong-integerallocation

Size of ints and longs?


I wrote this code:

#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;
}    

Where the output was:

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

Naturally, there are differences between integers and floating point data types, but what is the reason behind any compiler allocating the same amount of memory to a long as it does to an int? The long was designed to handle larger values, but is put to no use if done like the above(for the case of the integer). The floating point long variety adds an additional 16 bits of allocation.

My question then, in essence, is why have the long if there will be instances of machines that make no use of its abilities?

From a K&R ebook:

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.

Is there a "rule of thumb," if you will, for when a machine's compiler will opt to allocate more memory for a long than an int? And vice versa? What is the criteria?


Solution

  • Is there a "rule of thumb," if you will, for when a machine's compiler will opt to allocate more memory for a long than an int? And vice versa? What is the criteria?

    The criterion is likely "Will the target machine take advantage of a larger type?" or "Does the target machine have native registers and/or instructions which operate on this larger type?"