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

后端 未结 19 1856
谎友^
谎友^ 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条回答
  •  梦毁少年i
    2021-01-30 16:08

    Computer memory is subdivided into consecutively-addressed chunks of a certain size (often 8 bits, and referred to as bytes), and most computers are designed to efficiently access sequences of bytes that have consecutive addresses.

    If an object's address never changes within the object's lifetime, then code given its address can quickly access the object in question. An essential limitation with this approach, however, is that if an address is assigned for address X, and then another address is assigned for address Y which is N bytes away, then X will not be able to grow larger than N bytes within the lifetime of Y, unless either X or Y is moved. In order for X to move, it would be necessary that everything in the universe that holds X's address be updated to reflect the new one, and likewise for Y to move. While it's possible to design a system to facilitate such updates (both Java and .NET manage it pretty well) it's much more efficient to work with objects that will stay in the same location throughout their lifetime, which in turn generally require that their size must remain constant.

提交回复
热议问题