Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 753
Ukula Udan Avatar asked Jun 12 '18 14:06

Ukula Udan


People also ask

Why do variables have types?

A variable's type determines the values that the variable can have and the operations that can be performed on it.

Is Char smaller than short?

In practice, char is usually 8 bits in size and short is usually 16 bits in size (as are their unsigned counterparts).

Which of the following is the smallest possible value of char variable?

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).

Is bool smaller than char?

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."


1 Answers

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.

like image 63
SergeyA Avatar answered Oct 19 '22 16:10

SergeyA