Why are types always a certain size no matter its

2020-05-14 21:13发布

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 certain amount of memory no matter its value? For example, if I created the following integer with the value of 255

int myInt = 255;

Then myInt would occupy 4 bytes with my compiler. However, the actual value, 255 can be represented with only 1 byte, so why would myInt not just occupy 1 byte of memory? Or the more generalized way of asking: 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?

标签: c++
19条回答
Juvenile、少年°
2楼-- · 2020-05-14 22:19

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.

查看更多
登录 后发表回答