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

后端 未结 19 1838
谎友^
谎友^ 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 16:10

    Why does a type have only one size associated with it when the space required to represent the value might be smaller than that size?

    Primarily because of alignment requirements.

    As per basic.align/1:

    Object types have alignment requirements which place restrictions on the addresses at which an object of that type may be allocated.

    Think of a building that has many floors and each floor has many rooms.
    Each room is your size (a fixed space) capable of holding N amount of people or objects.
    With the room size known beforehand, it makes the structural component of the building well-structured.

    If the rooms are not aligned, then the building skeleton won't be well-structured.

提交回复
热议问题