Layering Multiple Conditions, Explained with Code Examples

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 →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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++?
They combine or flip bool values. && (AND) is true only when both sides are true. || (OR) is true when at least one side is true, including when both are. ! (NOT) takes one operand and is true when that operand is false. A single & or | is a different, bitwise operator, so avoid it in conditions.
How does short-circuit evaluation protect against division by zero in C++?
Short-circuit evaluation skips the right side of && when the left side is already false. Put the safety check first: if (count != 0 && total / count > 5). When count is 0, the left side is false, so the division never runs. If you reverse the two tests, the division happens first, which is undefined behavior.
How do you use De Morgan's laws to negate a compound condition?
Negate each part and flip the connector. !(a && b) is the same as !a || !b, and !(a || b) is the same as !a && !b. For example, !(x > 0 && x < 100) becomes x <= 0 || x >= 100. Negating > gives <=, not <, so the boundary value falls on exactly one side.
Why does the condition a < b < c or day == 6 || 7 compile but give the wrong result in C++?
Both compile, but neither means what it appears to. In a < b < c, the expression a < b yields true or false, and that result is then compared with c. In day == 6 || 7, the 7 is a nonzero value that counts as true, so the whole condition is always true. Write a < b && b < c and day == 6 || day == 7 instead.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

C++ Programming
3 credits · NCCRS
Enroll →