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?
Primarily because of alignment requirements.
As per basic.align/1:
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.