C - Logical Operators
Logical operators in C are used to combine or invert boolean expressions. They are essential for decision making in control flow statements.
Learning Objectives
- Use &&,||, and!correctly.
- Explain short-circuit behavior and truthiness.
Prerequisites
List of Logical Operators
- &&Logical AND
- ||Logical OR
- !Logical NOT
Short-circuit Evaluation
a && b evaluates b only if a is true (nonzero). a || b evaluates b only if a is false (zero).
#include <stdio.h>
int side(char *name, int v) { printf("%s\n", name); return v; }
int main(void) {
    int x = 1, y = 0;
    if (side("left", x) && side("right", y)) {
        printf("both\n");
    }
    if (side("left", x) || side("right", y)) {
        printf("one or both\n");
    }
}
Output shows when the right side is skipped.
Truthiness
Zero is false; nonzero is true. Logical operators return 0 or 1 in C.
Common Pitfalls
- Using &or|(bitwise) when you meant&&or||(logical).
- Expecting logical operators to preserve non-boolean operand values—they normalize to 0 or 1.
Checks for Understanding
- When is a || b’s right side evaluated?
- What is !42?
Show answers
- Only if ais false (0).
- 0 (false).
Summary
Logical operators are fundamental for writing conditions and controlling program flow in C. Understand short-circuiting to avoid unintended side effects.