In C language, logical operators are used to combine multiple conditions or expressions, typically in conditional statements (if, while, etc.). These operators help control the flow of a program by evaluating multiple conditions together. There are three main logical operators in C: logical AND (&&), logical OR (||), and logical NOT (!). The result of a logical operation is either true (non-zero, usually 1) or false (0).

List of Logical Operators

  1. Logical AND (&&):

    • Returns true if both operands are true. If either operand is false, the result is false.
    • Used when you want to check if all given conditions are true.
    • Example:
      int a = 5, b = 10; if (a > 0 && b > 0) { // This block will execute because both conditions are true. }
  2. Logical OR (||):

    • Returns true if at least one operand is true. The result is false only if both operands are false.
    • Used when you want to check if any given condition is true.
    • Example:
      int a = 5, b = -3; if (a > 0 || b > 0) { // This block will execute because at least one condition (a > 0) is true. }
  3. Logical NOT (!):

    • Reverses the truth value of the operand. If the operand is true, it returns false, and vice versa.
    • Used to invert a condition.
    • Example:
      int a = 5; if (!(a < 0)) { // This block will execute because a is not less than 0. }

Examples of Usage in Conditions

Logical operators are often used to create complex conditional statements:

#include <stdio.h> int main() { int x = 5, y = 10, z = 15; // Logical AND if (x > 0 && y > 0 && z > 0) { printf("All numbers are positive.\n"); } // Logical OR if (x > 10 || y > 10 || z > 10) { printf("At least one number is greater than 10.\n"); } // Logical NOT if (!(x > 10)) { printf("x is not greater than 10.\n"); } return 0; }

Short-Circuit Evaluation

  • AND (&&): If the first operand is false, the second operand is not evaluated because the whole expression will be false.
  • OR (||): If the first operand is true, the second operand is not evaluated because the whole expression will be true.

For example:

int a = 0, b = 10; if (a != 0 && b / a > 1) { // This will not evaluate "b / a" since "a != 0" is false, avoiding division by zero. }

Important Points

  1. Return Values: Logical operators return 1 (true) or 0 (false).
  2. Combining Conditions: Logical operators are useful for combining multiple conditions in if, while, or for statements.

Summary

  • Logical AND (&&): true if all conditions are true.
  • Logical OR (||): true if at least one condition is true.
  • Logical NOT (!): Inverts the truth value of a condition.

Logical operators are essential for controlling the flow of a program by allowing you to combine and manipulate conditions effectively, making decision-making more flexible and powerful.