Logical Operators and Short-Circuit Evaluation, Explained

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

← Relational Operators: Testing Relationships Between ValuesNext lesson: Simple and Two-Way Decisions: if and if-else →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
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

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.

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?
They are C's logical operators, and each produces 1 for true or 0 for false. a && b is 1 only when both sides are non-zero, a || b is 1 when at least one side is non-zero, and !a flips the result, turning 0 into 1 and any non-zero value into 0. The single & and | are different operators that work on the bits of a number.
What is the order of precedence for !, && and || in C?
C evaluates ! first, then &&, and || last, much as multiplication is done before addition. So 1 || 0 && 0 means 1 || (0 && 0), which is 1, while (1 || 0) && 0 is 0. Because mixing && and || is easy to misread, clang warns about && within || and suggests parentheses. Writing them makes the grouping clear to every reader.
What is short-circuit evaluation in C?
Short-circuit evaluation means C evaluates a logical expression from left to right and stops as soon as the result is certain. If the left side of && is false, the whole expression is false, so the right side is never evaluated. If the left side of || is true, the result is already true. Any increment or function call on the skipped side does not happen.
How can short-circuiting prevent a division by zero in C?
Put the safety test on the left of &&, so the risky part runs only when the test passes. In players != 0 && tokens / players >= 20, a player count of zero makes the left side false, and the division is skipped. Reversing the two sides would divide by zero first, which is undefined behavior for integers and can crash the program.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) 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 Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 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 Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 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 Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →