C++ Boolean

What is a Boolean?

A bool variable can hold only one of two values: true or false.

bool isOnline = true;
bool isEmpty = false;

Behind the scenes, true is usually represented as 1 and false as 0.

Logical Operators

  • && → AND
  • || → OR
  • ! → NOT
bool a = true, b = false;

cout << (a && b) << endl; // false (0)
cout << (a || b) << endl; // true (1)
cout << (!a) << endl;     // false (0)

Boolean in Conditions

Booleans are commonly used in if statements:

bool isLoggedIn = true;

if (isLoggedIn) {
    cout << "Welcome!";
} else {
    cout << "Access denied.";
}

Boolean Expressions

You can assign the result of comparisons to a boolean variable:

int age = 18;
bool canVote = (age >= 18);
cout << canVote;  // 1

Truthy and Falsy Values

In conditional checks, 0 is treated as false, and any non-zero number is treated as true:

if (0) {
    cout << "Will not print";
}

if (5) {
    cout << "Will print";
}

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic