Logical Operators in C

Logical operators (&&, ||, !) combine conditions, return 1 (true) or 0 (false).

Non-zero = true, zero = false. Short-circuit evaluation for efficiency.

1. The Three Logical Operators

&& (AND): True if both true.

|| (OR): True if either true.

! (NOT): Reverses truth value.

2. Truth Tables

TEXT
Logical operator truth tables
A    B    A&&B   A||B   !A
0    0     0      0     1
0    1     0      1     1
1    0     0      1     0
1    1     1      1     0

3. Basic Example

C
Logical operators demonstration
#include <stdio.h>
int main() {
    int a = 5, b = 10, c = 0;
    
    printf("a&&b = %d\n", a > 0 && b > 0);   // 1
    printf("a||c = %d\n", a > 0 || c > 0);   // 1
    printf("!c    = %d\n", !c);              // 1
    
    return 0;
}

Output: 1, 1, 1

4. Short-Circuit Evaluation

&&: Second operand skipped if first false.

||: Second operand skipped if first true.

C
Short-circuit example
int safeDivide(int a, int b) {
    if (b != 0 && a / b > 2) {  // b checked first!
        return 1;
    }
    return 0;
}

5. Common Use Cases

C
Real-world examples
// Valid age range
if (age >= 18 && age <= 65) { }

// Multiple menu options
if (choice == 1 || choice == 2 || choice == 3) { }

// Pointer safety
if (ptr != NULL && *ptr > 0) { }

6. Operator Precedence

! > && > || (left to right)

C
Precedence matters
int result = !a && b || c;  // (!a) && b || c

Use parentheses for clarity.

7. Practice Problems

1. Check leap year conditions

2. Validate triangle sides

3. Simple calculator menu