Search code examples
ctypesinteger

Why does the int type change size based on processor architecture while other types do not?


I am studying coding conventions and came across a rule that advises against using the int type. I believe this stems from the characteristic of the int type, which dynamically changes its size based on the processor's bit architecture.

My question is, why are other data types designed to have fixed sizes while the int type is designed to vary depending on the processor's bit architecture? If there are advantages to this approach, why aren't other data types designed to dynamically change their size as well?


Solution

  • All of signed char, short, int, long, long long and their unsigned equivalents may change size depending on target (same with floating point types). Each has a minimum required value range that they must support (limits.h), but they can be bigger.

    They are that way for historical reasons. Back in the dark ages, people had not figured out the meaning of portability. Some confused ideas floated around like "if I can always use int no matter system then that's portable". And so they let the types vary depending on system. The problem is that when writing truly portable code, you do quite often need to assume an exact value range or byte size of a type. And since you can't do that with int & friends, they because the opposite of portable. It's simply a poorly designed type system inherited from the 1970s and these types should simply be avoided in most professional contexts.

    The only types that are designed to have fixed sizes are those in stdint.h like int8_t, int16_t and so on. These are much more portable since you know the size and the signedness format and can adapt the program accordingly.