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

Short-circuit evaluation in logical OR

Short-circuit evaluation in logical OR

What you'll learn: Understand how the C compiler saves time (and avoids errors) by skipping the second half of an OR expression if the first half is already true.

The "Good Enough" Logic

In C, the logical OR operator (||) is used to check if at least one condition is true. However, the C compiler is inherently lazy—in a very efficient way. Because an OR expression only needs one single part to be true for the entire statement to be true, the compiler stops checking as soon as it finds a "true" value.

Imagine you are standing at the entrance of a party. The bouncer says, "You can enter if you have a VIP pass OR if you are on the guest list." If you hand him a VIP pass, he doesn't bother checking the guest list. He already has enough information to let you in. This "stopping early" is what we call short-circuit evaluation.

How it works in code

In the expression (A || B), the computer evaluates A first. If A is non-zero (true), the computer completely ignores B. It doesn't even look at it.

This is extremely useful for preventing crashes. Look at this example:

#include <stdio.h>

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

    // The first condition (people == 0) is TRUE.
    // The second condition (cookies / people > 2) is never checked.
    if (people == 0 || cookies / people > 2) {
        printf("We can't divide the cookies or there are too few!\n");
    }

    return 0;
}

If the computer evaluated both sides, the program would crash because you cannot divide by zero. Because of short-circuiting, the program sees people == 0 is true, decides the whole if is true, and skips the dangerous math on the right side entirely.

Watch out for side effects

While short-circuiting is a great safety net, it can be a trap if you put "work" on the right side of an OR. If you write if (a == 1 || ++b > 5), and a is indeed 1, the variable b will never be incremented. The code on the right simply never runs. Always ensure that the right side of your || doesn't contain critical logic that must happen every time.

Key takeaway

C evaluates OR expressions from left to right and stops immediately if the first part is true, ignoring the rest of the statement.