3.4 — And, or, not
Read one box at a time. No rush.
Combining questions#
Sometimes one question is not enough. "Is it sunny and warm?" C++ has three logical operators:
| Operator | Means | True when... |
|---|---|---|
&& | and | both sides are true |
|| | or | at least one side is true |
! | not | flips true ↔ false |
&& (and)#
C++
int age { 20 };bool hasTicket { true };bool canEnter { age >= 18 && hasTicket }; // true|| (or)#
C++
bool isWeekend { false };bool isHoliday { true };bool dayOff { isWeekend || isHoliday }; // true! (not)#
C++
bool isRaining { false };bool goOutside { !isRaining }; // trueChecking a range#
To check if a number is between two values, you need &&:
C++ — right ✓
bool isTeen { age >= 13 && age <= 19 };C++ — wrong ✗
bool isTeen { 13 <= age <= 19 }; // does NOT work like math!Watch out
C++ cannot chain comparisons like math does. Always split them up with &&.
Tip: press ← / → to move between lessons, / to search.