Are you logical?

Here's a detailed code sample illustrating the use of logical operators in C with explanations and output:

#include <stdio.h>

int main() {
    // Logical AND (&&)
    int a = 1, b = 0;
    printf("Logical AND: %d && %d = %d\n", a, b, a && b);

    // Logical OR (||)
    printf("Logical OR: %d || %d = %d\n", a, b, a || b);

    // Logical NOT (!)
    printf("Logical NOT: !%d = %d, !%d = %d\n", a, !a, b, !b);

    // Combining Logical Operators
    int x = 5, y = 10, z = 0;
    printf("\nCombining Logical Operators:\n");
    printf("%d && %d || %d = %d\n", x, y, z, x && y || z);

    // Short-Circuit Evaluation
    int result;
    result = (x > 0) && (y / x > 1);  // y / x is not evaluated if x <= 0
    printf("\nShort-Circuit Evaluation: %d\n", result);

    // Truthy and Falsy Values
    int value = 0;
    printf("\nTruthy and Falsy Values:\n");
    if (value) {
        printf("Value is truthy\n");
    } else {
        printf("Value is falsy\n");
    }

    // De Morgan's Laws
    int p = 1, q = 0;
    printf("\nDe Morgan's Laws:\n");
    printf("!(%d && %d) = %d\n", p, q, !(p && q));
    printf("!(%d || %d) = %d\n", p, q, !(p || q));

    return 0;
}

Explanation:

  1. Logical AND (&&):

    • Returns 1 (true) if both operands are true, otherwise 0 (false).

    • Example: 1 && 0 = 0

  2. Logical OR (||):

    • Returns 1 (true) if at least one operand is true, otherwise 0 (false).

    • Example: 1 || 0 = 1

  3. Logical NOT (!):

    • Returns 1 (true) if the operand is false, and vice versa.

    • Examples: !1 = 0, !0 = 1

  4. Combining Logical Operators:

    • Illustrates combining logical AND and OR.

    • Example: 5 && 10 || 0 = 1 (true)

  5. Short-Circuit Evaluation:

    • Demonstrates that the second condition is not evaluated if the first condition is false.

    • Example: (5 > 0) && (10 / 5 > 1) evaluates to 1 (true)

  6. Truthy and Falsy Values:

    • Shows that in C, 0 is considered falsy, and any non-zero value is truthy.

    • Example: Value is falsy

  7. De Morgan's Laws:

    • Illustrates De Morgan's Laws for negating logical expressions.

    • Examples: !(1 && 0) = 1, !(1 || 0) = 0

Output:

Logical AND: 1 && 0 = 0
Logical OR: 1 || 0 = 1
Logical NOT: !1 = 0, !0 = 1

Combining Logical Operators:
5 && 10 || 0 = 1

Short-Circuit Evaluation: 1

Truthy and Falsy Values:
Value is falsy

De Morgan's Laws:
!(1 && 0) = 1
!(1 || 0) = 0

This code provides a clear demonstration of how logical operators work in C, including short-circuit evaluation, truthy and falsy values, and De Morgan's Laws.