Logical Operators
The logger reports "average too high" when the day's average passes 25.0 degrees. On the first morning after a reset, there are no readings yet, and a careless check would divide by zero. One operator, used in the right order, prevents the crash for free.
The rule
&& and || stop the moment the answer is known.
C has three logical operators:
&&(AND) is true when both sides are true.||(OR) is true when at least one side is true.!(NOT) is true when its operand is false.
Like comparisons, they treat zero as false and anything else as true, and they always produce the int 1 or 0. So !5 is 0, !0 is 1, and !!x turns any value into a clean 1 or 0.
The rule that makes them powerful is short-circuit evaluation. The left side is evaluated first, and:
&&skips its right side when the left side is false, because the result must be 0.||skips its right side when the left side is true, because the result must be 1.
That lets the left side guard the right:
if (count != 0 && total / count > 250) {
printf("average too high\n");
}When count is 0, the division never happens. Swap the two conditions and the division runs first, and integer division by zero is undefined behaviour.
Precedence: ! binds tightest, then comparisons, then &&, then ||. So a || b && c means a || (b && c). When mixing && and ||, add parentheses; the compiler's -Wall will suggest them anyway.
De Morgan's laws let you push a ! inside: !(a && b) equals !a || !b, and !(a || b) equals !a && !b. The "reading is outside the safe range" test is !(t >= 0 && t <= 300), which becomes t < 0 || t > 300.
The shortcut
Read left to right and stop as soon as the answer is fixed. For &&, stop at the first false. For ||, stop at the first true. Anything after the stopping point does not run at all.
Start on the left
countis 0, socount != 0is 0 (false).
Drills
Answer fast — trust the rule.
What is the value of !5?
With int n = 0;, what happens in int ok = (n != 0 && 10 / n > 1);?
What is the value of 1 || 0 && 0?
After int calls = 0; int r = (1 == 1) || (calls = 1);, what is calls?
What is the value of !!42?
Remember
- && and || stop the moment the answer is known; the right side may never run.
- Shortcut: put the guard on the left, such as
count != 0 && total / count > 250. - Trap:
&&binds tighter than||; add parentheses whenever you mix them.
