Skip to main content

Section 7.1 Boolean Values and Variables

Decisions in programming are generally made based on choices where the only possible answers are either true or false. A program’s behavior might depend on "did the user enter the right password?", "is the mouse over this button?", or "is the result less than 0?". All of those are questions that have a true/false (yes/no) answer.
Values that can only be true or false are known as β€œboolean” values, named after the mathematician George Boole who developed an algebraic way of representing true/false logic.
In C++, the bool type is used to represent boolean values. You can declare and assign them like other variables. In this example, the first line is a variable declaration, the second is an assignment, and the third is both:
bool flag;                // declare a variable that holds true/false
flag = true;              // set the variable to hold true
bool testResult = false;  // declare a variable and set it to false
If you try to print a boolean variable, it will display as 1 (true) or 0 (false). In fact, there is a general convention that 0 is false and any other value is true. It is syntactically legal to set boolean variables using numeric values, but once you store a number into a bool it becomes either 1 or 0:
#include <iostream>
using namespace std;

int main() {
    bool iAmHappy = 6;   // legal, but does not make much sense
    cout << iAmHappy;
}

Checkpoint 7.1.1.

You have attempted of activities on this page.