Booleans - true and false values

Why Booleans Take a Byte of Memory

If booleans only store true/false, why do they take up a whole byte of memory?

3D art showing a wizard character

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.

Memory Access Efficiency

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

Memory Alignment

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.

Space vs Speed Tradeoff

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.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved