0
0
CHow-ToBeginner · 3 min read

How to Use Logical Operators in C: Syntax and Examples

In C, logical operators && (AND), || (OR), and ! (NOT) combine or invert boolean expressions. Use && to check if both conditions are true, || to check if at least one is true, and ! to reverse a condition's truth value.
📐

Syntax

Logical operators in C are used to combine or modify conditions that evaluate to true (non-zero) or false (zero).

  • expr1 && expr2: True if both expr1 and expr2 are true.
  • expr1 || expr2: True if either expr1 or expr2 is true.
  • !expr: True if expr is false; it reverses the condition.
c
if (condition1 && condition2) {
    // code runs if both conditions are true
}

if (condition1 || condition2) {
    // code runs if at least one condition is true
}

if (!condition) {
    // code runs if condition is false
}
💻

Example

This example shows how to use logical operators to check multiple conditions and print messages accordingly.

c
#include <stdio.h>

int main() {
    int a = 5;
    int b = 10;

    if (a > 0 && b > 0) {
        printf("Both a and b are positive.\n");
    }

    if (a == 5 || b == 5) {
        printf("Either a or b is 5.\n");
    }

    if (!(a < 0)) {
        printf("a is not negative.\n");
    }

    return 0;
}
Output
Both a and b are positive. Either a or b is 5. a is not negative.
⚠️

Common Pitfalls

Common mistakes when using logical operators in C include:

  • Using a single & or | instead of && or ||. The single versions are bitwise operators, not logical.
  • Not using parentheses to group conditions, which can cause unexpected results due to operator precedence.
  • Confusing assignment = with equality == inside conditions.
c
#include <stdio.h>

int main() {
    int x = 1;
    int y = 0;

    // Wrong: bitwise AND instead of logical AND
    if (x & y) {
        printf("This won't print because bitwise AND is 0.\n");
    }

    // Correct: logical AND
    if (x && y) {
        printf("This won't print because y is 0 (false).\n");
    } else {
        printf("Logical AND correctly evaluates to false.\n");
    }

    // Wrong: assignment instead of comparison
    if (x == 0) {
        printf("This runs if x is 0.\n");
    } else {
        printf("Assignment in condition can cause bugs.\n");
    }

    return 0;
}
Output
Logical AND correctly evaluates to false. Assignment in condition can cause bugs.
📊

Quick Reference

OperatorMeaningExampleResult
&&Logical AND5 > 0 && 3 < 10true (1) if both true
||Logical OR5 == 5 || 3 > 10true (1) if either true
!Logical NOT! (5 > 10)true (1) if condition false

Key Takeaways

Use && for AND, || for OR, and ! for NOT to combine or invert conditions in C.
Always use double operators (&&, ||) for logical operations, not single (&, |).
Use parentheses to group conditions clearly and avoid confusion.
Avoid using = inside conditions; use == to compare values.
Logical operators return 1 for true and 0 for false in C.