UPI Study › Courses › C++ Programming › Free lessons › Lesson 4.2 Free with a free account
Layering Multiple Conditions
C++ Programming · Chapter 4: Decision MakingSection 4.2 · lesson 22 of 84video coming soon
← Comparing Values in CodeNext lesson: Mapping Decision Paths Visually →
In this lesson
Combining facts with AND, OR and NOT.
- Combine conditions with &&, || and !
- Read and build a truth table
- Use short-circuit evaluation as a guard
- Apply De Morgan's laws safely
Transcript
Everything said in the video, section by section (1,227 words). Read along, or search it.
Opening Idea
Real Rules Combine Several Tests
Real rules are almost never a single test. A discount applies if the customer is a member, and the order is large enough. A form is rejected if the name is blank, or the date is missing. Logical operators combine several facts into one answer. And a careless combination gives a rule that is subtly, silently wrong.
Definitions
AND, OR, and NOT Operators
Relational operators each answer one question with a bool. Logical operators combine those answers, and produce a bool in turn, so they chain indefinitely. Double ampersand is AND. It's true when both sides are true: age at least 18, and has an I D. Double bar is OR. It's true when at least one side is true: staff, or member. And OR is inclusive. Unlike tea or coffee in conversation, it's also true when both sides are. Has I D, or member: both hold, and it's true. The exclamation mark is NOT. It takes a single operand, written in front, and is true when that operand is false. One warning. A single ampersand, or a single bar, is a different operator: it works on individual bits. In a condition it often appears to work, and that is exactly what makes the one-character slip dangerous.
Truth Tables
Listing Every Input Combination
A truth table lists every combination of inputs, and the result for each. Two conditions give four combinations. Here is the whole table, printed. The left column is AND, the right column is OR. AND is true in just one corner: both true. Every other row is false. OR is the opposite shape: false in just one corner, where neither holds, and true everywhere else. Three conditions give eight rows, and four give sixteen. Tedious, but never unreliable. When reasoning fails, the table tells you what a condition really says.
Short-Circuiting
Stopping Once the Answer Is Certain
C plus plus doesn't always evaluate both sides. It works left to right, and stops the moment the answer is certain. That's short-circuit evaluation. For AND, a false left side makes the whole thing false, no matter what. So the right side is never evaluated. Watch the increment on the right. X starts at 5. The left side, x less than 0, is false, so the plus plus never runs.
Quick Check
Predict the Value After OR
Quick check. Now OR: x is still 5, and the left side, x greater than 0, is true. Does the increment run? Pause, and predict the printed x.
Answer
A True Left Side Skips the Right
Still 5. For OR, a true left side makes the whole thing true regardless, so the right side is skipped. Only when the left side doesn't settle it does the right side run. Left true, AND continues, and now x becomes 6. It follows from the truth tables. And it isn't just efficiency: it lets a condition protect its own second half.
Practical Use
Guarding Against Division by Zero
Put the check first, and the dangerous operation second, and the dangerous operation simply never runs when it would be unsafe. Count not equal to 0, and total over count greater than 5. With a count of 0, the left side is false, so the division never happens. Reverse those two tests, and the division runs first, by zero, before the guard is even consulted. That's undefined behavior. The order is the whole point. Checking that an index is less than the size, before reading data at that index, works the same way.
Warning
Skipped Side Effects Hide Bugs
But there's another edge to the same blade. Because the right side may be skipped, anything it does may be skipped too. A function in a condition that records an attempt, or sends a message, would run only sometimes, depending on the first half. That is a genuinely hard bug to find. Conditions should ask questions, not do work.
Precedence
Arithmetic, Comparison, Then Logic
Mixing arithmetic, comparison and logic in one expression is normal, and precedence is arranged so the natural reading is usually right. Arithmetic binds first. Then comparisons. Then AND, tighter than OR. Assignment is loosest, so the whole condition is worked out first. Here, age is 20, points are 40, and vip is true. Points plus 10 is 50, so the first comparison is true. Age less than 18 is false. Then AND goes before OR: true and false is false. False or true is true.
Common Mistakes
Three Surprising Groupings
Three groupings catch people out. Not ready, double equals done, groups as not-ready, compared with done. NOT applies to ready alone, which is almost never what was meant. Not x greater than 5 groups as not x, then compared with 5. Write the not, with x greater than 5 in parentheses. And a or b and c groups as a or, b and c. That's correct, but easy to misread, so parenthesize it.
De Morgan's Laws
Negate Each Part, Flip Connector
Negated compound conditions are hard to read, and easy to get wrong. De Morgan's laws move a negation inside without changing the meaning. Not, a and b, is the same as not a, or not b. And not, a or b, is the same as not a, and not b. Negate each part, and flip the connector. The connector always flips. Keeping it is the classic error. In plain English, not both means at least one fails. Not either means both fail. You don't have to trust the law. Here are the four rows: the two columns match on every one.
Applying the Laws
Negating Real Conditions Correctly
Here are the laws on real conditions. Not, age at least 18 and has an I D, becomes age less than 18, or no I D. Not, is empty or is locked, becomes not empty, and not locked. Not, x above 0 and below 100, becomes x at most 0, or x at least 100. Notice that last one: negating greater than gives less than or equal, not less than. The boundary belongs to exactly one side. Use whichever form states the rule the way a person would say it.
Readability
Naming Pieces for Quick Verification
A compound condition is a claim about the world, and the next reader has to verify it. So make that quick. This long condition is correct, but nobody can check it at a glance. Split it into named pieces: is adult, in good standing, can pay. Now the final test reads as a sentence, and each name documents intent a bare comparison can't. Parenthesize whenever you mix AND and OR. Prefer positive names: is ready beats not-not-ready. Never write ready double equals true. And keep actions out of conditions.
Silent Errors
Two Conditions That Compile but Lie
Two conditions compile without errors, and lie. A less than b less than c doesn't test whether b lies between the others. A less than b produces true or false, and that answer is then compared with c. The compiler warns, but it builds. Day equals 6 or 7 doesn't ask whether the day is 6 or 7. It asks whether day equals 6, or whether 7 counts as true. And 7 always counts as true. Write both comparisons out: a less than b, and b less than c. Day equals 6, or day equals 7. Every comparison needs both of its sides.
Key Takeaways
Summary and a Logging Puzzle
To summarize. AND needs both sides. OR needs at least one, and is inclusive. NOT flips a single operand. Short-circuiting stops as soon as the answer is certain, so a guard placed first protects what follows it. Arithmetic first, then comparison, then logic, AND before OR. And De Morgan: negate each part, and flip the connector. Here's something to think about. A condition reads, attempts left greater than 0, or record failure, where that function writes a log entry. What's wrong with it?
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Layering Multiple Conditions
What do the &&, ||, and ! operators do in C++?
How does short-circuit evaluation protect against division by zero in C++?
How do you use De Morgan's laws to negate a compound condition?
Why does the condition a < b < c or day == 6 || 7 compile but give the wrong result in C++?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →