3.4 — And, or, not

📘 Chapter 3⏱ about 1 min read✍️ Beginner friendly
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:

OperatorMeansTrue when...
&&andboth sides are true
||orat least one side is true
!notflips 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 };   // true

Checking 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 &&.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.