As already discussed in the docs, a bool
data type occupies at least a byte of memory. A similar question was asked on SO before (How a bool type variable is stored in memory? (C++)), but this discussion and the documentation only seem to discuss the amount of space occupied by a boolean data type, not what actually happens in memory when I do this:
bool b = true;
So what does actually happen in memory? What happens to the 7 bits that are not used in storing this information? Does the standard prescribe behavior for this?
Are they undefined? Or did someone at C++ headquarters just do this:
enum bool : char
{
false = 0,
true = 1
};
Internally, a Boolean variable is a 2-byte value holding –1 (for TRUE) or 0 (for FALSE). Any type of data can be assigned to Boolean variables. When assigning, non-0 values are converted to TRUE , and 0 values are converted to FALSE. When appearing as a structure member, Boolean members require 2 bytes of storage.
bool The bool type takes one byte and stores a value of true (1) or false(0).
In computer science, the Boolean (sometimes shortened to Bool) is a data type that has one of two possible values (usually denoted true and false) which is intended to represent the two truth values of logic and Boolean algebra.
Because it's fast. A 32-bit processor typically works with 32-bit values. Working with smaller values involves longer instructions, or extra logic.
The standard doesn't mandate anything for the binary representation of bools; it just says that, when converting to other integral types, a true
bool will become 1 and a false
bool will become 0.
This of course suggests an implementation similar in spirit to the one you said, where such conversions would become essentially no-ops or plain integer widening (but remember that bool
is mandated to be a primitive type, not an enumeration type).
Standard states that bool
values behave as integral types, yet it doesn't specify their concrete representation in memory:
"Values of type bool
are either true
or false
. As described below, bool
values behave as integral types. Values of type bool
participate in integral promotions" ~ C++03 3.9.1 §6
"A synonym for integral type is integer type. The representations of integral types shall define values by use of a pure binary numeration system" ~ C++03 3.9.1 §7
Yet it defines the integral promotion from bool
to int
:
"An rvalue of type bool
can be converted to an rvalue of type int
, with false
becoming zero and true
becoming one. These conversions are called integral promotions." ~ C++03 4.5 §4-5
as well as conversion from other types to bool
:
"A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
." ~ C++03 4.12 §1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With