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?
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-sizedbool
or implies that only one variable has a smallest size.sizeof(bool) is implementation-defined.
Is sizeof(bool) defined?
Namely, it is not required to only be a single byte.
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.
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:
(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:
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++)?"
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 andint
is either 2 or 4, but usually 4 bytes long.The C++ standard gives following relations:
...