Logical operators
- C++ course
- Beginner
- Lesson 27/116
- 4 min
Learn boolean logic with &&, || and !.
Logical operators
Logical operators combine bool values: && (AND), || (OR), ! (NOT).
&& gives true only when both sides are true. || gives true when at least one side is true. ! flips the value: !true = false.
Example: (age >= 18) && (hasLicense) is true when both age is 18+ and a license is held. (isWeekend) || (isHoliday) is true on weekends or holidays. These operators let you build complex conditions.
Short-circuit evaluation
C++ uses short-circuit evaluation with logical operators: when the result is determined, the remaining side is not evaluated.
With &&, if the left side is false, the right side is skipped (the result is already false). With ||, if the left side is true, the right side is skipped (the result is already true).
This behavior lets you write safe conditions: (ptr != nullptr) && (ptr->value > 0). If ptr is null, the right side is never evaluated, preventing a crash. Understanding short-circuit helps you write safer code.
Practice Print logical results
Inside main, declare bool ready = true; and bool loaded = false;. Perform two logical operations: bool canFire = ready && loaded; and bool either = ready || loaded;. Print both on separate lines with std::cout using std::endl.
Starter code
#include <iostream>
int main() {
// Declare ready and loaded
// Do logical operations and print them
return 0;
}Sample solution
#include <iostream>
int main() {
// Declare ready and loaded
// Do logical operations and print them
bool ready = true;
bool loaded = false;
bool canFire = ready && loaded;
bool either = ready || loaded;
std::cout << canFire << std::endl;
std::cout << either << std::endl;
return 0;
}Expected output
0 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the result of true && false?
- true (1)
- Undefined
- Error
- false (0) Correct answer
Explanation: && requires both sides true; if one is false the result is false.
2 Match logical operators
| Term | Meaning |
|---|---|
&& |
And |
|| |
Or |
! |
Not |
short-circuit |
Early exit |
3 Logical and
bool canFire = ready ____ loaded;
bool canFire = ready && loaded;
Explanation: && gives true only when both sides are true.