Short-circuit evaluation of ||
What you'll learn: How C saves time by stopping logical OR evaluations as soon as the outcome is certain.
In C, the logical OR operator (||) is quite lazy—but in a very smart way. This behavior is known as short-circuit evaluation. To understand it, we first need to remember how || works: it returns true if either the left side or the right side is true. Because of this simple rule, C takes a shortcut whenever possible.
The "First Success" Rule
Imagine you are looking for your house keys. You check your pocket (the left side), and you find them! Do you then continue to search the kitchen counter (the right side)? Of course not. You already have what you need.
C applies this same logic to expressions. If the expression on the left side of || evaluates to true (non-zero), C doesn't even look at the expression on the right. It already knows the entire statement must be true, so it stops immediately. The right-hand side is never executed.
Seeing it in Action
This isn't just a fun fact; it changes how your code runs. If the right-hand side of your || contains a function call or a variable change, that action might never happen.
#include <stdio.h>
int main() {
int cookiesInJar = 10;
int isHungry = 1; // 1 is true
// Because isHungry is true, C "short-circuits"
// It never checks if cookiesInJar-- > 0
if (isHungry || cookiesInJar-- > 0) {
printf("Time to eat!\n");
}
// cookiesInJar is still 10! The decrement never ran.
printf("Cookies left: %d\n", cookiesInJar);
return 0;
}
Why This Matters
Short-circuiting is incredibly useful for safety. You can use the left side of a || to "guard" the right side. For example, if you are checking if a division result is greater than 10, you can write if (x == 0 || 100 / x > 10).
If x is zero, the left side is true. C stops there and never performs the 100 / x calculation. This prevents the program from crashing due to a division-by-zero error. Without short-circuiting, the computer would try to calculate both sides and crash immediately.
Key takeaway
The || operator stops evaluating as soon as it finds a true value on the left, ignoring the right side entirely.