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?
A variable's type determines the values that the variable can have and the operations that can be performed on it.
In practice, char is usually 8 bits in size and short is usually 16 bits in size (as are their unsigned counterparts).
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
However, my C++ book (C++ Pocket Reference, O'Reilly) states: "The typical size of a bool is one byte," and "The size of a char is one byte. The size of a byte technically is implementation defined, but it is rarely anything but eight bits."
Because types fundamentally represent storage, and they are defined in terms of maximum value they can hold, not the current value.
The very simple analogy would be a house - a house has a fixed size, regardless of how many people live in it, and there is also a building code which stipulates the maximum number of people who can live in a house of a certain size.
However, even if a single person is living in a house which can accommodate 10, the size of the house is not going to be affected by the current number of occupants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With