Course contentsShow
← C
Lesson 170 of 1,2193. Operators and ExpressionsFree lesson

Short-circuit evaluation of `&&`

Short-circuit evaluation of &&

What you'll learn: How C saves time and prevents crashes by stopping a logical "AND" evaluation early if the first condition is false.

The Lazy Genius

In C, the logical AND operator (&&) is very efficient. When you use &&, the computer looks at the left side first. If the left side is false, the computer doesn't even bother looking at the right side. It "short-circuits" and immediately decides the whole expression is false.

Think of it like a safety check at a theme park. If a sign says, "You must have a ticket AND be over 48 inches tall to ride," the worker checks your ticket first. If you don't have a ticket, they don't bother measuring your height. The result is already a "no."

Why This Matters

Short-circuiting isn't just about speed; it is a powerful tool for preventing errors. Sometimes, checking the second condition would cause the program to crash if the first condition isn't met.

A common example is division. You cannot divide a number by zero. By using short-circuiting, you can check if a number is zero before you try to use it in a calculation.

#include <stdio.h>

int main() {
    int cookies = 10;
    int people = 0;

    // The first part (people > 0) is false.
    // C stops here and never tries to divide by zero!
    if (people > 0 && (cookies / people) > 2) {
        printf("Everyone gets plenty of cookies!\n");
    } else {
        printf("No cookies distributed.\n");
    }

    return 0;
}

In the code above, if C evaluated (cookies / people) when people was 0, the program would crash. Because of short-circuiting, the computer sees people > 0 is false, skips the division entirely, and moves straight to the else block.

Side Effect Warning

Because the right side might never run, you should avoid putting important actions (like incrementing a variable with ++) on the right side of a &&. If the left side is false, that variable will never be updated, which can lead to confusing bugs in your logic.

Key takeaway

The && operator stops evaluating as soon as it finds a false value, allowing you to place "safety checks" on the left to protect the code on the right.