c++clinuxoperating-system

Who decides the sizeof any datatype or structure (depending on 32 bit or 64 bit)?


Who decides the sizeof any datatype or structure (depending on 32 bit or 64 bit)? The compiler or the processor? For example, sizeof(int) is 4 bytes for a 32 bit system whereas it's 8 bytes for a 64 bit system.

I also read that sizeof(int) is 4 bytes when compiled using both 32-bit and 64-bit compiler.

Suppose my CPU can run both 32-bit as well as 64-bit applications, who will play main role in deciding size of data the compiler or the processor?


Solution

  • It's ultimately the compiler. The compiler implementors can decide to emulate whatever integer size they see fit, regardless of what the CPU handles the most efficiently. That said, the C (and C++) standard is written such, that the compiler implementor is free to choose the fastest and most efficient way. For many compilers, the implementers chose to keep int as a 32 bit, although the CPU natively handles 64 bit ints very efficiently.

    I think this was done in part to increase portability towards programs written when 32 bit machines were the most common and who expected an int to be 32 bits and no longer. (It could also be, as user user3386109 points out, that 32 bit data was preferred because it takes less space and therefore can be accessed faster.)

    So if you want to make sure you get 64 bit ints, you use int64_t instead of int to declare your variable. If you know your value will fit inside of 32 bits or you don't care about size, you use int to let the compiler pick the most efficient representation.

    As for the other datatypes such as struct, they are composed from the base types such as int.