I am not sure whether you are asking why int
objects have fixed sizes instead of variable sizes or whether you are asking why int
objects have the fixed sizes they do. This answers the former.
We do not want the basic types to have variable lengths. That makes it very complicated to work with them.
We want them to have fixed lengths, because then it is much easier to generate instructions to operate on them. Also, the operations will be faster.
If the size of an int
were variable, consider what happens when you do:
b = 3;
b += 100000;
scanf("%d", &b);
When b
is first assigned, only one byte is needed. Then, when the addition is performed, the compiler needs more space. But b
might have neighbors in memory, so the compiler cannot just grow it in place. It has to release the old memory and allocate new memory somewhere.
Then, when we do the scanf
, the compiler does not know how much data is coming. scanf
will have to do some very complicated work to grow b
over and over again as it reads more digits. And, when it is done, how does it let you know where the new b
is? The compiler has to have some mechanism to update the location for b
. This is hard and complicated and will cause additional problems.
In contrast, if b
has a fixed size of four bytes, this is easy. For the assignment, write 3 to b
. For the addition, add 100000 to the value in b
and write the result to b
. For the scanf
, pass the address of b
to scanf
and let it write the new value to b
. This is easy.