Notifications
Clear all
Topic starter 01/08/2025 11:27 pm
In C++, Boolean statements are all about making decisions—your code asks “Is this true?” and acts accordingly. Let’s break it down 🧠🔧
✅ What Is a Boolean?
A Boolean is a data type that can hold one of two values:
true
(which equals1
)false
(which equals0
)
You declare it using the bool
keyword:
bool isCodingFun = true;
bool isFishTasty = false;
🔍 Using Booleans in Conditions
Booleans are most commonly used in if
statements:
bool isSunny = true;
if (isSunny) {
std::cout << "Let's go outside!";
} else {
std::cout << "Better stay in.";
}
- If
isSunny
istrue
, the first block runs. - If it’s
false
, theelse
block runs.
🧪 Boolean Expressions
You can create Boolean values using comparison operators:
int x = 10;
std::cout << (x > 5); // Outputs 1 (true)
std::cout << (x == 10); // Outputs 1 (true)
std::cout << (x < 3); // Outputs 0 (false)
🔗 Logical Operators
Combine multiple Boolean expressions:
int age = 20;
bool hasTicket = true;
if (age >= 18 && hasTicket) {
std::cout << "Welcome to the concert!";
}
&&
→ AND||
→ OR!
→ NOT
🧠 Boolean Conversion
C++ treats 0
as false
and any non-zero value as true
:
bool result = 100; // true
bool empty = 0; // false
You can also use std::boolalpha
to print true
/false
instead of 1
/0
:
std::cout << std::boolalpha << result; // Output: true