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+
The answer is char
. No other answer is correct.
(Though I agree the question should have been worded better).
The C++03 Standard $5.3.3/1 says:
sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined. [Note: in particular, sizeof(bool) and sizeof(wchar_t) are implementation-defined.69)
(Found this info from another question: Why the sizeof(bool) is not defined to be one, by the Standard itself?).
Given that the minimum size is 1 (sizeof must return integral values), this means that the following will be true in any implementation that follows the standards:
sizeof(char) == 1
sizeof(bool) >= 1
sizeof(int) >= 1
sizeof(float) >= 1
The question was poorly phrased and probably should have been asked more clearly as "...which variable would necessarily occupy no more space in memory than any other (in any well-behaved standard implementation of C++)?"
The correct answer is boolean in theory, as a char requires knowledge of at least 8 bits, while a bool technically only requires one bit. you could smash 8 bools inside of a single char if you wanted to in theory.
There is no guarantee for the exact size of these types, but there is a guarantee, that char is not bigger than short, and short is not bigger than long.
So, char will always occupy the least amount of memory, but it might not be the only one to do so. It's still guaranteed, that nothing else will have a smaller size.
There might be an exception with bool, however, on some special embedded microcontrollers. They can have a bit
variable, which takes exactly one bit, however, they are not in RAM but in special registers.
However, unless your architecture and compiler are especially strange or unusual, you can reasonalbly expect that char
is 1, short
is 2, long
is 4, long long
is 8 and int
is either 2 or 4, but usually 4 bytes long.
The typical size of a bool
is one byte. does not means it always is one byte. The question either refers to a realization that have not one-byte-sized bool
or implies that only one variable has a smallest size.