UPI Study › Courses › Programming in C › Free lessons › Lesson 4.3 Free with a free account
Logical Operators and Short-Circuit Evaluation
Programming in C · Chapter 4: Conditional Logic, Decision Structures, and Practical ApplicationsSection 4.3 · lesson 21 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Simple and Two-Way Decisions: if and if-else →← Relational Operators: Testing Relationships Between ValuesNext lesson: Simple and Two-Way Decisions: if and if-else →
In this lesson
How C combines yes-or-no tests with AND, OR and NOT.
- Evaluate expressions built with &&, || and ! using truth tables
- Apply the precedence of NOT, AND and OR, adding parentheses when they mix
- Explain how short-circuit evaluation can skip the right-hand side
- Use a left-side check to guard against division by zero
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (986 words). Read along, or search it.
Opening Question
A Ride Sign With Three Conditions
The Rocket Ride at the Starlight Arcade has a sign. You must be at least one hundred ten centimeters tall, and either ten or older, or with a grown-up. That's three small questions tangled into one rule, and the gate guard answers them in a blink. So does a nine-year-old who's tall enough, and here with her dad, get on? A program can decide, with three tiny operators.
Truth Tables
AND, OR and NOT in C
A logical operator takes yes-or-no values, the ones and zeros from comparisons, and gives back a new yes or no. C has three. a AND b, written with two ampersands, needs both to hold, like needing a ticket and a token. a OR b, written with two vertical bars, needs just one, like paying by card or by cash. And NOT a, an exclamation mark, flips the answer. This program prints every combination, a truth table. AND gives one only in the last row, where both are one. OR gives zero only in the first row, where both are zero. And NOT turns zero into one, and one into zero. Notice the symbols are doubled. A single ampersand or bar is a different operator, which works on the bits of a number. You almost always want the doubled ones. By the way, this one-and-zero logic is called Boolean, after George Boole, an English mathematician who wrote about it in the eighteen hundreds.
Worked Example
Turning the Rocket Ride Sign Into Code
Real rules have several parts, so break them up. Priya, who builds the arcade's software, turns the Rocket Ride sign into code. Her rider is nine years old and one hundred twenty centimeters tall, and arrives with a grown-up. Each small question becomes a variable whose name reads like a question: tall, and old. The last lines join them. Run it. Tall enough is one, but old enough is zero. Even so, old or with an adult is one. The grown-up saves the day. So tall, AND, in parentheses, old OR adult, is one. She may ride. And the NOT in front gives the sign's opposite: not allowed is zero. Those parentheses matter. They decide which part is worked out first.
Precedence
NOT Before AND Before OR
Without parentheses, C works out NOT first, then AND, and OR last, just as multiplying beats adding. So one OR zero AND zero means one OR the result of zero AND zero. That's one. With parentheses around the OR part, the same values give zero. Clang flags the mix. Its warning says AND within OR, and its note suggests parentheses around the AND part. So when a rule mixes the two, always write the parentheses. Then nobody has to remember the ranking.
Quick Check
Predicting Two Membership Tests
Quick check, with a new rule. A player isn't a member, scored six hundred twenty, and hasn't played today. The program prints two tests about that player. What does it print? Pause and predict. Build and run it. It prints one, then zero. Not member is one, and the score is over five hundred, so the first test is one. In the second, the parentheses give one, because the score is enough. But played is zero, and one AND zero is zero.
Short-Circuit Evaluation
C Stops Once the Answer Is Certain
If you're checking that a cookie jar is empty and its lid is on, you stop the moment you see the jar is full. C does the same. It works from left to right, and short-circuits: it stops as soon as the answer is certain. With AND, a false left side makes the whole thing false, so the right side is never looked at. With OR, a true left side settles it. You can watch it happen. Here each right side adds one to a counter called calls. If calls stays zero, the right side never ran. Run it. False AND: the right side ran zero times. True AND: once. True OR: zero times. And false OR: once. One caution. In real code, don't hide an action like this on the right side, because a reader may forget it can be skipped. Here it's only a way to peek.
Guard Pattern
A Left-Side Check Prevents Division by Zero
That gives you a protective trick: put the safety check on the left. Here, ninety tokens are shared among the players, and the test asks whether each gets twenty or more. But there are zero players. The left side, players not equal to zero, is false. So the division, tokens divided by players, never happens. The answer is simply zero. Swap the sides, and C would divide by zero first. For whole numbers that's undefined behavior, and it can crash the program. The left side stands guard.
stdbool.h
The bool Type With true and false
Since C99, the header stdbool dot h gives the type bool, and the words true and false, which mean one and zero. Now yes-or-no variables say what they are. Can play is has ticket, AND not closed, AND tokens at least four. A bool also tidies whatever you put in it. Store forty-two, and it holds one. C treats every non-zero number as true, so a AND b, five AND three, is one. And not-not seven is a quick way to turn any non-zero into exactly one.
Quick Check
Right Sides That Never Run
Quick check. A player has three lives and no bonus. Two tests each try to add one to bonus on their right side. What are ok and bonus at the end? Pause and predict. Build and run it. It prints zero, zero. In the first test, lives greater than zero is true, and OR stops right there. In the second, lives greater than five is false, and AND stops there. Neither right side ran, so bonus is still zero, and ok ends as zero.
Key Takeaways
Logical Operators in Review
To sum up. AND needs both sides, OR needs one, and NOT flips. Each gives one or zero. NOT ranks first, then AND, then OR, so write parentheses whenever a rule mixes them. C works left to right and stops once the answer is certain, so a check on the left can guard the right. And stdbool dot h gives bool, true, and false.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. 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 All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C 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 Logical Operators and Short-Circuit Evaluation
What do the &&, || and ! operators do in C?
What is the order of precedence for !, && and || in C?
What is short-circuit evaluation in C?
How can short-circuiting prevent a division by zero in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →