Course contentsShow
← C
Lesson 253 of 1,2194. Control FlowFree lesson

Short-circuit evaluation in logical AND

Short-circuit evaluation in logical AND

What you'll learn: How the computer skips unnecessary checks in a logical AND operation to save time and prevent crashes.

The Lazy Gatekeeper

Imagine you are a security guard at a VIP club. To let someone in, they must meet two criteria: they must have an invitation AND they must be wearing formal shoes.

If a guest walks up and tells you, "I don't have an invitation," do you even bother looking at their feet? Of course not. It doesn't matter if they are wearing the fanciest shoes in the world; they already failed the first requirement, so they aren't getting in.

In C, the logical AND operator (&&) works exactly like that lazy gatekeeper. This behavior is called short-circuit evaluation.

How it works in code

In an expression like (A && B), C evaluates the conditions from left to right. If A is false (zero), the entire expression is guaranteed to be false. C doesn't even look at B. It simply stops and moves on.

This isn't just about efficiency; it's a vital safety feature. Take a look at this common pattern:

#include <stdio.h>

int main() {
    int count = 0;
    int total = 100;

    // We want to calculate the average, but only if count is not zero
    // to avoid a "Division by Zero" crash.
    if (count != 0 && (total / count) > 10) {
        printf("High average!\n");
    } else {
        printf("Average unavailable or too low.\n");
    }

    return 0;
}

In the code above, count is 0. When the if statement runs, it checks the first part: count != 0. This evaluates to false.

Because of short-circuiting, C stops right there. It never attempts to calculate (total / count). If C did try to check that second part, the program would crash because you cannot divide by zero. By placing the safety check on the left, you protect the risky code on the right.

Why this matters

Short-circuiting allows you to write concise code without nesting multiple if statements inside one another. You can check if a pointer exists before accessing its data, or check if an array index is within bounds before looking at the value at that index, all in a single line.

Key takeaway

C stops evaluating a logical AND (&&) as soon as it finds a false condition, which saves time and prevents risky code from executing.