I read that C compilers must allocate 2 bytes for the type short and must allocate 4 bytes for the type long. So, depending on the system the type int can have 2 bytes or 4 bytes. So, what's the purpose of it? If we need a 2 byte number, we can use short and if we need a 4 byte number, we can use long. I feel like int is like gambling if the system is 16-bit or not. (I generally don't understand why C can't decide by itself how much memory is needed for number, just like Python does)
In B, the ancestor of C, the only type was int
. It was the size of a “machine word”, which is generally to say the size of a register—16 bits on a 16-bit system, 32 bits on a 32-bit system, and so forth. C simply preserved this type. short
and long
were introduced as ways of controlling storage space when less or more range was needed. This matters when available memory is constrained: why allocate a long
when you know a value will never exceed the range of a short
?
I generally don't understand why C can’t decide by itself how much memory is needed for number, just like Python does
Python decides this dynamically, using an arbitrary-precision representation. C decides this statically, and requires that it be specified by the programmer. There are statically typed languages in which type annotations are not required, due to type inference. If you want arbitrary-precision integers in C, you can use GMP, which provides mpz_t
and a host of other types and functions for arbitrary-precision arithmetic.