The boolean type

The type bool

Let us learn a new type of variable: The type bool. A variable of type bool represents a boolean. That means it can only be equal to either true of false.

Here is an example:

bool doIUnderstand; doIUnderstand = true; doIUnderstand = false;

The word true actually is a keyword that equals 1. false is also a keyword and it equals 0. That means that the following is equivalent to the two lines of code above:

doIUnderstand = 1; doIUnderstand = 0;

We usually use the value 1 to represent the meaning true. However, the truth is that a variable of type bool is considered to be true as long as it does not equal 0.


In C++, the type bool exists by default. However, in C, the boolean type (bool) used to not exist and it is not defined by default. In order to use it in C, we must include the header file <stdbool.h>. Note, however, that if an (very) old C compiler that does not support (relatively) new features is used, the header might not exist.

Using the bool type is not essential as any variable which value is 0 can be considered to represent false and true otherwise. The advantage of using that type is that it makes it clearer for people reading the code that the variable represents a boolean (true or false) instead of a plain number.

Size of the boolean type

How many binary digits (bits) are required to be able to represent 2 values? One (21). Does that mean the size of a variable of type bool is 1 bit? No. Computers can not directly access individual bits. The smallest amount of memory they can directly work with is a byte. Therefore, a variable can not have a size smaller than 1 byte. For that reason, the type bool usually have a size of one byte, which usually contains 8 bits.

That is not very memory efficient, but us, programmers, have to deal with the limitations of the hardware used. There are tricks to use, indirectly, the bits of a variable to represent booleans, but it is more complex and it is slower than using whole bytes. We will see how to do that later.