The following is from a "fill-in at home" programming test that is part of the application process for an MSc in game development at a UK university:
C++ Basics
If a program declared four variables, one of type
int
, one of typefloat
, one of typechar
, and one of typebool
, which variable would occupy the least space in memory?
- int
- char
- float
- bool
According to the instructions, there is only one true statement. 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."
Am I misunderstanding something here? What answer would you put and why?
No type takes less than
char
, because by definitionsizeof(char) == 1
. However, it is entirely possible that all types take the same amount of space.(Representing each type with 16 bits (with a suitably unusual floating point format) would suffice to satisfy the standard value range requirements; real hardware where every type has 32 bits exists.)
The language doesn't specify any relationships between these type sizes that guarantee a correct answer to that question as posed. They could all be 32-bit types, for example.
The real problem with the question your have posted lies in these words:
occupy ... space in memory
If an interpretation is to be assumed, then in most occasions you would assume one of the current popular compilers in which case answer
2
and4
would both occupy the least space in memory. Simply because the current popular compilers make thechar
andbool
occupy a single byte in memory...As outlined in the comments,
sizeof() is of type size_t
, which is integral.As
sizeof(char) == 1
is always true as per the standard, and the value is integral; no othersizeof(T)
can be lower than1
. But any otherT
thanchar
can be bigger than1
dependening on the implementation. As you can't assume thatsizeof(char) == sizeof(bool)
always holds, you can at least assume thatsizeof(char) <= sizeof(bool)
holds.Which makes
sizeof(char)
being the least the most correct answer...I think the correct answer should be 2. By definition, char is the smallest addressable unit.
Also see: Why is a char and a bool the same size in c++?