Why are types always a certain size no matter its value?

后端 未结 19 1854
谎友^
谎友^ 2021-01-30 15:22

Implementations might differ between the actual sizes of types, but on most, types like unsigned int and float are always 4 bytes. But why does a type always occupy a certai

19条回答
  •  余生分开走
    2021-01-30 15:47

    It is an optimization and simplification.

    You can either have fixed sized objects. Thus storing the value.
    Or you can have variable sized objets. But storing value and size.

    fixed sized objects

    The code that manipulates number does not need to worry about size. You assume that you always use 4 bytes and make the code very simple.

    Dynamic sized objects

    The code the manipulates number must understand when reading a variable that it must read the value and size. Use the size to make sure all the high bits are zero out in the register.

    When place the value back in memory if the value has not exceeded its current size then simply place the value back in memory. But if the value has shrunk or grown you need to move the storage location of the object to another location in memory to make sure it does not overflow. Now you have to track the position of that number (as it can move if it grows too large for its size). You also need to track all the unused variable locations so they can potentially be reused.

    Summary

    The code generated for fixed size objects is a lot simpler.

    Note

    Compression uses the fact that 255 will fit into one byte. There are compression schemes for storing large data sets that will actively use different size values for different numbers. But since this is not live data you don't have the complexities described above. You use less space to store the data at a cost of compressing/de-compressing the data for storage.

提交回复
热议问题