Coming Soon
This lesson is currently being developed
Boolean values
Learn about boolean data type and logical values.
What to Expect
Comprehensive explanations with practical examples
Interactive coding exercises to practice concepts
Knowledge quiz to test your understanding
Step-by-step guidance for beginners
Development Status
Content is being carefully crafted to provide the best learning experience
Preview
Early Preview Content
This content is still being developed and may change before publication.
4.9 — Boolean values
In this lesson, you'll learn about the bool
data type, which represents logical true/false values, and how to use boolean values effectively in your programs.
What are boolean values?
Boolean values represent logical states: either true or false. The bool
data type is named after George Boole, a mathematician who developed Boolean algebra - the foundation of computer logic.
Think of boolean values like a light switch - it can only be in one of two states: ON (true) or OFF (false). There's no "maybe" or "partially on" - it's definitively one or the other.
The bool data type
In C++, the bool
type can store exactly two values: true
or false
.
#include <iostream>
int main()
{
std::cout << "Boolean basics:\n\n";
// Declaring boolean variables
bool isReady = true;
bool isFinished = false;
bool hasPermission = true;
std::cout << "Boolean values:\n";
std::cout << "isReady: " << isReady << std::endl;
std::cout << "isFinished: " << isFinished << std::endl;
std::cout << "hasPermission: " << hasPermission << std::endl;
// Show size of bool
std::cout << "\nSize of bool: " << sizeof(bool) << " byte(s)\n";
// Boolean literals
std::cout << "\nBoolean literals:\n";
std::cout << "true: " << true << std::endl;
std::cout << "false: " << false << std::endl;
return 0;
}
Output:
Boolean basics:
Boolean values:
isReady: 1
isFinished: 0
hasPermission: 1
Size of bool: 1 byte(s)
Boolean literals:
true: 1
false: 0
Boolean output and std::boolalpha
By default, boolean values print as 1
(true) or 0
(false). You can change this behavior:
#include <iostream>
int main()
{
bool success = true;
bool error = false;
std::cout << "Default boolean output:\n";
std::cout << "success: " << success << std::endl;
std::cout << "error: " << error << std::endl;
// Use std::boolalpha to print "true"/"false"
std::cout << std::boolalpha; // Enable text output
std::cout << "\nWith std::boolalpha:\n";
std::cout << "success: " << success << std::endl;
std::cout << "error: " << error << std::endl;
// Use std::noboolalpha to switch back to numbers
std::cout << std::noboolalpha; // Disable text output
std::cout << "\nBack to numeric output:\n";
std::cout << "success: " << success << std::endl;
std::cout << "error: " << error << std::endl;
return 0;
}
Output:
Default boolean output:
success: 1
error: 0
With std::boolalpha:
success: true
error: false
Back to numeric output:
success: 1
error: 0
Boolean expressions and comparisons
Boolean values often come from comparison operations:
#include <iostream>
int main()
{
std::cout << std::boolalpha; // Show true/false instead of 1/0
int age = 25;
int height = 175; // cm
double temperature = 98.6;
std::cout << "Comparison results:\n";
// Equality and inequality
bool isAdult = (age >= 18);
bool isTall = (height > 180);
bool isEqual = (age == 25);
bool isNotEqual = (age != 30);
std::cout << "age >= 18: " << isAdult << std::endl;
std::cout << "height > 180: " << isTall << std::endl;
std::cout << "age == 25: " << isEqual << std::endl;
std::cout << "age != 30: " << isNotEqual << std::endl;
// Multiple comparisons
bool isNormalTemp = (temperature >= 97.0 && temperature <= 99.5);
bool isYoungOrTall = (age < 30 || height > 170);
std::cout << "\nComplex expressions:\n";
std::cout << "Normal temperature: " << isNormalTemp << std::endl;
std::cout << "Young or tall: " << isYoungOrTall << std::endl;
return 0;
}
Output:
Comparison results:
age >= 18: true
height > 180: false
age == 25: true
age != 30: true
Complex expressions:
Normal temperature: true
Young or tall: true
Boolean operators
C++ provides several operators that work with boolean values:
Logical NOT (!)
#include <iostream>
int main()
{
std::cout << std::boolalpha;
bool isLoggedIn = true;
bool isGuest = false;
std::cout << "Logical NOT operator (!):\n";
std::cout << "isLoggedIn: " << isLoggedIn << std::endl;
std::cout << "!isLoggedIn: " << !isLoggedIn << std::endl;
std::cout << "isGuest: " << isGuest << std::endl;
std::cout << "!isGuest: " << !isGuest << std::endl;
// Practical use
bool needsToLogin = !isLoggedIn;
std::cout << "\nPractical example:\n";
std::cout << "User needs to login: " << needsToLogin << std::endl;
return 0;
}
Output:
Logical NOT operator (!):
isLoggedIn: true
!isLoggedIn: false
isGuest: false
!isGuest: true
Practical example:
User needs to login: false
Logical AND (&&)
#include <iostream>
int main()
{
std::cout << std::boolalpha;
bool hasAccount = true;
bool knowsPassword = true;
bool isAccountActive = false;
std::cout << "Logical AND operator (&&):\n";
std::cout << "hasAccount && knowsPassword: " << (hasAccount && knowsPassword) << std::endl;
std::cout << "hasAccount && isAccountActive: " << (hasAccount && isAccountActive) << std::endl;
// All conditions must be true
bool canLogin = hasAccount && knowsPassword && isAccountActive;
std::cout << "\nCan login (all conditions): " << canLogin << std::endl;
// Truth table demonstration
std::cout << "\nAND truth table:\n";
std::cout << "true && true: " << (true && true) << std::endl;
std::cout << "true && false: " << (true && false) << std::endl;
std::cout << "false && true: " << (false && true) << std::endl;
std::cout << "false && false: " << (false && false) << std::endl;
return 0;
}
Output:
Logical AND operator (&&):
hasAccount && knowsPassword: true
hasAccount && isAccountActive: false
Can login (all conditions): false
AND truth table:
true && true: true
true && false: false
false && true: false
false && false: false
Logical OR (||)
#include <iostream>
int main()
{
std::cout << std::boolalpha;
bool isWeekend = false;
bool isHoliday = true;
bool isSick = false;
std::cout << "Logical OR operator (||):\n";
std::cout << "isWeekend || isHoliday: " << (isWeekend || isHoliday) << std::endl;
std::cout << "isWeekend || isSick: " << (isWeekend || isSick) << std::endl;
// Any condition can be true
bool staysHome = isWeekend || isHoliday || isSick;
std::cout << "\nStays home (any condition): " << staysHome << std::endl;
// Truth table demonstration
std::cout << "\nOR truth table:\n";
std::cout << "true || true: " << (true || true) << std::endl;
std::cout << "true || false: " << (true || false) << std::endl;
std::cout << "false || true: " << (false || true) << std::endl;
std::cout << "false || false: " << (false || false) << std::endl;
return 0;
}
Output:
Logical OR operator (||):
isWeekend || isHoliday: true
isWeekend || isSick: false
Stays home (any condition): true
OR truth table:
true || true: true
true || false: true
false || true: true
false || false: false
Short-circuit evaluation
Logical operators use short-circuit evaluation - they stop evaluating as soon as the result is known:
#include <iostream>
bool expensiveCheck()
{
std::cout << "Expensive check performed!\n";
return true;
}
bool quickCheck()
{
std::cout << "Quick check performed!\n";
return false;
}
int main()
{
std::cout << std::boolalpha;
std::cout << "Short-circuit AND (&&):\n";
std::cout << "Result: " << (quickCheck() && expensiveCheck()) << std::endl;
std::cout << "(expensiveCheck() was not called because quickCheck() returned false)\n\n";
std::cout << "Short-circuit OR (||):\n";
bool alwaysTrue = true;
std::cout << "Result: " << (alwaysTrue || expensiveCheck()) << std::endl;
std::cout << "(expensiveCheck() was not called because first condition was true)\n\n";
std::cout << "Without short-circuit:\n";
bool result = quickCheck() && expensiveCheck();
std::cout << "This time expensiveCheck() will not be called due to short-circuit\n";
return 0;
}
Output:
Short-circuit AND (&&):
Quick check performed!
Result: false
(expensiveCheck() was not called because quickCheck() returned false)
Short-circuit OR (||):
Result: true
(expensiveCheck() was not called because first condition was true)
Without short-circuit:
Quick check performed!
This time expensiveCheck() will not be called due to short-circuit
Converting other types to boolean
Other data types can be converted to boolean values:
#include <iostream>
int main()
{
std::cout << std::boolalpha;
std::cout << "Converting numbers to boolean:\n";
// Integer conversions
std::cout << "bool(0): " << bool(0) << std::endl;
std::cout << "bool(1): " << bool(1) << std::endl;
std::cout << "bool(42): " << bool(42) << std::endl;
std::cout << "bool(-5): " << bool(-5) << std::endl;
// Floating-point conversions
std::cout << "\nFloating-point conversions:\n";
std::cout << "bool(0.0): " << bool(0.0) << std::endl;
std::cout << "bool(3.14): " << bool(3.14) << std::endl;
std::cout << "bool(-0.1): " << bool(-0.1) << std::endl;
// Pointer conversions
int x = 10;
int* ptr = &x;
int* nullPtr = nullptr;
std::cout << "\nPointer conversions:\n";
std::cout << "bool(valid_pointer): " << bool(ptr) << std::endl;
std::cout << "bool(nullptr): " << bool(nullPtr) << std::endl;
// Practical usage
std::cout << "\nPractical usage in conditions:\n";
int count = 0;
if (count) // Equivalent to: if (count != 0)
{
std::cout << "Count is non-zero\n";
}
else
{
std::cout << "Count is zero\n";
}
return 0;
}
Output:
Converting numbers to boolean:
bool(0): false
bool(1): true
bool(42): true
bool(-5): true
Floating-point conversions:
bool(0.0): false
bool(3.14): true
bool(-0.1): true
Pointer conversions:
bool(valid_pointer): true
bool(nullptr): false
Practical usage in conditions:
Count is zero
Practical applications
User interface logic
#include <iostream>
int main()
{
std::cout << std::boolalpha;
// User settings
bool isDarkMode = true;
bool hasNotifications = false;
bool isPremium = true;
bool isLoggedIn = true;
std::cout << "User Interface Settings:\n";
std::cout << "Theme: " << (isDarkMode ? "Dark" : "Light") << " mode\n";
std::cout << "Notifications: " << (hasNotifications ? "Enabled" : "Disabled") << "\n";
// Feature availability
bool canAccessPremiumFeatures = isLoggedIn && isPremium;
bool shouldShowAds = !isPremium && isLoggedIn;
std::cout << "\nFeature Availability:\n";
std::cout << "Can access premium features: " << canAccessPremiumFeatures << "\n";
std::cout << "Should show ads: " << shouldShowAds << "\n";
return 0;
}
Game logic
#include <iostream>
int main()
{
std::cout << std::boolalpha;
// Game state
bool isGameRunning = true;
bool playerAlive = true;
bool hasKey = false;
bool doorLocked = true;
int playerHealth = 75;
int playerScore = 1250;
std::cout << "Game Status:\n";
std::cout << "Game running: " << isGameRunning << "\n";
std::cout << "Player alive: " << playerAlive << "\n";
std::cout << "Player health: " << playerHealth << "\n";
// Game logic
bool isLowHealth = (playerHealth < 25);
bool canOpenDoor = hasKey || !doorLocked;
bool hasHighScore = (playerScore > 1000);
bool gameOver = !playerAlive || !isGameRunning;
std::cout << "\nGame Logic:\n";
std::cout << "Low health warning: " << isLowHealth << "\n";
std::cout << "Can open door: " << canOpenDoor << "\n";
std::cout << "Has high score: " << hasHighScore << "\n";
std::cout << "Game over: " << gameOver << "\n";
return 0;
}
Input validation
#include <iostream>
bool isValidAge(int age)
{
return age >= 0 && age <= 150;
}
bool isValidEmail(const std::string& email)
{
// Simplified email validation
bool hasAt = email.find('@') != std::string::npos;
bool hasDot = email.find('.') != std::string::npos;
bool notEmpty = !email.empty();
return notEmpty && hasAt && hasDot;
}
bool isStrongPassword(const std::string& password)
{
bool longEnough = password.length() >= 8;
bool hasUpper = false;
bool hasLower = false;
bool hasDigit = false;
for (char c : password)
{
if (c >= 'A' && c <= 'Z') hasUpper = true;
if (c >= 'a' && c <= 'z') hasLower = true;
if (c >= '0' && c <= '9') hasDigit = true;
}
return longEnough && hasUpper && hasLower && hasDigit;
}
int main()
{
std::cout << std::boolalpha;
// Test validation functions
std::cout << "Input Validation:\n\n";
std::cout << "Age validation:\n";
std::cout << "isValidAge(25): " << isValidAge(25) << "\n";
std::cout << "isValidAge(-5): " << isValidAge(-5) << "\n";
std::cout << "isValidAge(200): " << isValidAge(200) << "\n\n";
std::cout << "Email validation:\n";
std::cout << "isValidEmail(\"user@example.com\"): " << isValidEmail("user@example.com") << "\n";
std::cout << "isValidEmail(\"invalid\"): " << isValidEmail("invalid") << "\n\n";
std::cout << "Password validation:\n";
std::cout << "isStrongPassword(\"MyPass123\"): " << isStrongPassword("MyPass123") << "\n";
std::cout << "isStrongPassword(\"weak\"): " << isStrongPassword("weak") << "\n";
return 0;
}
Best practices with boolean values
✅ Use descriptive boolean variable names
// Good: Clear intent
bool isLoggedIn = true;
bool hasPermission = false;
bool canEdit = true;
bool shouldSave = false;
// Less clear
bool flag = true;
bool status = false;
bool check = true;
✅ Use boolean expressions directly
// Good: Direct boolean expression
bool isAdult = (age >= 18);
// Unnecessary: Comparing with true/false
// bool isAdult = (age >= 18) == true; // Redundant
// bool isMinor = (age >= 18) == false; // Better: age < 18
✅ Use meaningful function names for boolean functions
#include <iostream>
// Good: Functions that return boolean values
bool isEmpty(const std::string& text)
{
return text.length() == 0;
}
bool isPositive(int number)
{
return number > 0;
}
bool canVote(int age)
{
return age >= 18;
}
int main()
{
std::cout << std::boolalpha;
std::cout << "isEmpty(\"\"): " << isEmpty("") << "\n";
std::cout << "isPositive(-5): " << isPositive(-5) << "\n";
std::cout << "canVote(21): " << canVote(21) << "\n";
return 0;
}
❌ Common mistakes to avoid
#include <iostream>
int main()
{
bool isReady = true;
// Avoid: Redundant comparisons
// if (isReady == true) // Just use: if (isReady)
// if (isReady != false) // Just use: if (isReady)
// Avoid: Redundant boolean returns
// if (age >= 18)
// return true;
// else
// return false;
// Better: return age >= 18;
// Correct usage
if (isReady)
{
std::cout << "System is ready!\n";
}
return 0;
}
Summary
Boolean values are fundamental for representing logical states:
Key concepts:
bool
type stores exactly two values:true
orfalse
- Takes 1 byte of memory (though only needs 1 bit logically)
- Prints as
1
/0
by default, ortrue
/false
withstd::boolalpha
Boolean operators:
!
(NOT): Flips true/false&&
(AND): True only if both operands are true||
(OR): True if at least one operand is true- Short-circuit evaluation optimizes performance
Conversions:
0
and0.0
convert tofalse
- All other numeric values convert to
true
nullptr
converts tofalse
, valid pointers totrue
Best practices:
- Use descriptive names (
isReady
,hasPermission
) - Avoid redundant comparisons with
true
/false
- Use boolean expressions directly in conditions
- Name boolean functions clearly (
isEmpty
,canAccess
)
Quiz
- What are the two possible values of a
bool
variable? - What does the
&&
operator do? - How does short-circuit evaluation work?
- What boolean value does the integer
0
convert to? - What's wrong with writing
if (isReady == true)
?
Practice exercises
Try these boolean exercises:
- Write a function
isLeapYear(int year)
that returns true if the year is a leap year - Create a program that validates user input using multiple boolean conditions
- Implement a simple access control system using boolean logic
- Write functions that demonstrate all combinations of AND, OR, and NOT operations
Explore More Courses
Discover other available courses while this lesson is being prepared.
Browse CoursesLesson Discussion
Share your thoughts and questions