In C how much space does a bool (boolean) take up? Is it 1 bit, 1 byte or something else?
If you are referring to C99 _Bool
try:
printf("%zu\n", sizeof(_Bool)); /* Typically 1. */
Note the standard says:
6.2.5
An object declared as type
_Bool
is large enough to store the values 0 and 1.
The size cannot be smaller than one byte. But it would be legal to be larger than one byte.
The smallest addressable "thing" in C is a char
. Every variable in C must have a unique address, therefore your bool
can't be smaller than that. (Note that char
isn't always 8 bits though)
In older C standards, there was no such type defined. Many embedded microcontrollers, however, include special circuitry to allow for efficient processing of single-bit flags; some allow for such processing of variables stored anywhere, while others only allow it for variables stored in a particular region of memory. Compilers for such processors allow individual variables of static duration to be declared as type "bit"; such variables will generally only take one bit of storage (allocated, if necessary, within a region that can accommodate such usage). Some compilers will allow automatic variables of non-recursive routines to be declared as 'bit' type, but will silently regard them as 'static' (the linkers provided with such compilers require that routines identify which other routines they call, and will reject programs in which routines that are not tagged as re-entrant call each other in mutually-recursive fashion).
A few points worth noting:
- Processors whose compilers support "true" bit variables can generally set, clear, or branch upon the values of such variables faster and with less code than they could set, clear, or branch upon byte-wide flags;
- Many such processors have very small amounts of RAM. On many processors, question of whether individual variables (as distinct from array elements or structure fields) take a bit or a byte each wouldn't be worth worrying about. On a processor with 25 bytes of memory, however, there's a huge difference between having 16 flags taking one byte each, versus having all 16 flags combined into two bytes.
- At least on compilers I've seen, bit variables may not be used as structure fields nor array elements, nor may one take the address of one.
I don't know enough about C99 or later versions of the C or C++ standards to know whether they have any concept of a standalone bit type which doesn't have an address. I can't think of any reason such a thing shouldn't be possible, especially the standards already recognize the concept of things like structure bit-fields which behave much like lvalues but don't have addresses. Some linkers may not support such variables, but such linkers could be accommodated by making their actual size implementation-dependent (indeed, aside from program speed or total memory usage, it would be impossible to tell whether such variables were given 1 bit or 64 bits each).