This is a great question! Even though a boolean only needs a single bit (0 or 1) to store its value, in C++ and most other programming languages, booleans typically use a whole byte of memory. Let's explore why this design decision was made.
Modern computers are designed to access memory in chunks of bytes (8 bits), not individual bits. Trying to access individual bits would actually be slower than accessing whole bytes, because the computer would need to do extra work to figure out which bit to read or write.
Think of it like a library where books can only be accessed by shelf, not individually. Even if you only want one page from a book, you need to take the whole book off the shelf.
Here's a simple program that shows us the size of a boolean:
#include <iostream>
using namespace std;
int main() {
bool isAlive{true};
cout << "Size of bool: "
<< sizeof(isAlive) << " byte\n";
// We can have an array of booleans
bool flags[8]{true, false, true,
true, false, false, true, false};
cout << "Size of 8 bools: "
<< sizeof(flags) << " bytes";
}
Size of bool: 1 byte
Size of 8 bools: 8 bytes
Another reason for using a whole byte is memory alignment. Modern computers work most efficiently when data is aligned on certain boundaries. Using full bytes helps maintain this alignment without requiring special handling.
While it might seem wasteful to use 8 bits when we only need 1, the performance benefits of byte-aligned access usually outweigh the memory cost. In most programs, the extra memory used by booleans is negligible compared to other data types like integers (4 bytes) and floating-point numbers (4 or 8Â bytes).
If you do need to store many boolean values efficiently, C++ provides special container types like std::vector<bool>
which we'll learn about later that can pack multiple boolean values into single bytes.
Answers to questions are automatically generated and may not have been reviewed.
true
and false
valuesAn overview of the fundamental true or false data type, how we can create them, and how we can combine them.