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+
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++?
No type takes less than char
, because by definition sizeof(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.)
If a program declared four variables, one of type int, one of type float, one of type char, and one of type bool, which variable would occupy the least space in memory?
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
and 4
would both occupy the least space in memory. Simply because the current popular compilers make the char
and bool
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 other sizeof(T)
can be lower than 1
. But any other T
than char
can be bigger than 1
dependening on the implementation. As you can't assume that sizeof(char) == sizeof(bool)
always holds, you can at least assume that sizeof(char) <= sizeof(bool)
holds.
Which makes sizeof(char)
being the least the most correct answer...
The C++ standard gives following relations:
sizeof(char) == 1
sizeof(char) <= sizeof(int) <= sizeof(long)
sizeof(float) <= sizeof(double)
...
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.
sizeof(bool) is implementation-defined.
Is sizeof(bool) defined?
Namely, it is not required to only be a single byte.