Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the sizeof(int) == sizeof(long)?

In the program listed below, the sizeof(int) and sizeof(long) are equal on my machine (both equal 4 bytes (or 32 bits)). A long, as far as I know, is 8 bytes. Is this correct? I have a 64-bit machine

#include <stdio.h>
#include <limits.h>

int main(void){
    printf("sizeof(short) = %d\n", (int)sizeof(short));
    printf("sizeof(int) = %d\n", (int)sizeof(int));
    printf("sizeof(long) = %d\n", (int)sizeof(long));
    printf("sizeof(float) = %d\n", (int)sizeof(float));
    printf("sizeof(double) = %d\n", (int)sizeof(double));
    printf("sizeof(long double) = %d\n", (int)sizeof(long double));
    return 0;
}
like image 737
ChrisMcJava Avatar asked Sep 19 '13 17:09

ChrisMcJava


1 Answers

A long, as far as I know, is 8 bytes. Is this correct?

No, this is not correct. The C and C++ specifications only state that long must be greater than or equal to 32 bits. int can be smaller, but on many platforms, in C and C++, long and int are both 32 bits.

This is a very good reason to prefer fixed width integer types such as int64_t if they're available to you and you're using C99 or a framework which provides you an equivalent type.

like image 96
Reed Copsey Avatar answered Oct 13 '22 18:10

Reed Copsey