C Logical Operators – Master Conditional Logic in C

Logical operators in C allow you to combine multiple conditions and control the flow of your program. These are essential when using if statements, loops, and decision-making structures.

Why Use Logical Operators?

When you want to check more than one condition at a time, logical operators help you build compound expressions:

  • Is the user logged in AND has permission?

  • Is the value greater than 10 OR less than 5?

  • Is the user NOT an admin?

List of Logical Operators in C

OperatorNameDescriptionExample
&&Logical ANDTrue if both conditions are true(a > 0 && b > 0)
` `Logical OR
!Logical NOTReverses the result (true ↔ false)!(a > 0)

Example Program: Logical Operators in Action

#include <stdio.h>

int main() {
    int a = 5, b = -3;

    // Logical AND
    if (a > 0 && b > 0) {
        printf("Both a and b are positive.\n");
    } else {
        printf("At least one is not positive.\n");
    }

    // Logical OR
    if (a > 0 || b > 0) {
        printf("At least one is positive.\n");
    }

    // Logical NOT
    if (!(b > 0)) {
        printf("b is not positive.\n");
    }

    return 0;
}

Output:

At least one is not positive.
At least one is positive.
b is not positive.

Truth Table Summary

AND (&&)

ABA && B
000
010
100
111

OR (||)

ABA || B
000
011
101
111

NOT (!)

A!A
01
10

Best Practices for C Logical Operators

PracticeWhy?
Use parentheses to group conditionsImproves readability and correctness
Don’t rely on non-zero being true blindlyBe explicit with boolean logic
Understand short-circuitingPrevents unnecessary condition checks

What is Short-Circuit Evaluation?

Logical operators use short-circuiting:

  • For &&: if the first condition is false, the second is not checked.

  • For ||: if the first condition is true, the second is not checked.

if (a != 0 && (10 / a) > 2) { ... } // Safe: won't divide by 0

Common Mistakes to Avoid

MistakeProblem
Using & instead of &&Bitwise AND, not logical AND
Confusing !a with a == 0They’re not always the same
Forgetting parenthesesMay lead to incorrect logic order