Logical Operators in C

Logical operators in C are used to combine or negate conditions. They are mainly used in decision-making and looping statements.

Logical AND Operator (&&)

The logical AND operator returns true if both conditions are true.

Example: (a > 0 && b > 0)

Logical OR Operator (||)

The logical OR operator returns true if at least one condition is true.

Example: (a > 0 || b > 0)

Logical NOT Operator (!)

The logical NOT operator reverses the result of a condition.

Example: !(a > 0)

Truth Table of Logical Operators

  • AND (&&): true only if both operands are true
  • OR (||): true if any one operand is true
  • NOT (!): true if the operand is false

Short-Circuit Evaluation

C uses short-circuit evaluation, meaning the second condition may not be evaluated if the result is already known.

Common Mistakes

  • Using & instead of && and | instead of ||
  • Assuming logical operators return true or false keywords
  • Confusing logical operators with bitwise operators
  • Incorrect use of parentheses in complex expressions