I saw these question in our school’s past paper, and I’m wondering if this is a valid question.
How big is
bool
in C and C++?A) 1 bit
B) 4 bit
C) 8 bit
D) 1 byte
What is the smallest unit of memory C or C++ use?
A) 1 bit
B) 4 bit
C) 8 bit
D) 1 byte
The answer to both are D, but I am thinking if this is inappropriate.
EDIT: 1 byte is not necessarily 8 bits on some systems. See this StackOverflow post.
6
AFAIK, no answers presented here are correct. The size of bool
and _Bool
is not constrained to be 1 byte (I seem to remember that there is a constraint in C which forces sizeof(_Bool)<=sizeof(short)
which hasn’t an equivalent in C++)
7
I’d say the answers are both D) but the questions do leave a bit to be desired, for the first as AProgrammer points out, a bool could be bigger than 1 byte, for the second question it should clarify the smallest unit of addressable memory (bitfields allow a structure of multiple smaller memory units but they aren’t addressable)
to clarify why C) is not the answer, there may not be 8 bits in a byte in C || C++
hopefully its obvious why A) and B) are not correct
1
The size of bool in std::vector is 1 bit.
Vector of bool
This is a specialized version of vector, which is used for elements of type
bool
and optimizes for space.It behaves like the unspecialized version of vector, with the following changes:
- The storage is not necessarily an array of
bool
values, but the library implementation may optimize storage so that each value is stored in a single bit.- Elements are not constructed using the allocator object, but their value is directly set on the proper bit in the internal storage.
- Member function flip and a new signature for member swap.
- A special member type, reference, a class that accesses individual bits in the container’s internal storage with an interface that emulates a
bool
reference. Conversely, member typeconst_reference
is a plainbool
.- The pointer and iterator types used by the container are not necessarily neither pointers nor conforming iterators, although they shall simulate most of their expected behavior.
These changes provide a quirky interface to this specialization and favor memory optimization over processing (which may or may not suit your needs). In any case, it is not possible to instantiate the unspecialized template of vector for
bool
directly. Workarounds to avoid this range from using a different type (char
,unsigned char
) or container (like deque) to use wrapper types or further specialize for specific allocator types…
4