Monday, February 1, 2016

Logical operator

There are three logical operators in C language, &&, ||, !
OperatorNameDescriptionExample
&&'Logical AND' Operator'AND' operator returns true if both the operands it operates on evaluates to true (non-zero), else return falsea && b returns true if both a and b are non-zero
||'Logical OR' Operator'OR' operator returns true if any of the operands it operates on evaluates to true (non-zero), else return falsea || b returns true if either a or b are non-zero
!'Logical NOT' Operator'NOT' operator is a unary operator (it operates only on one operand). It returns true if the operand is false and returns false if the operand is true!a returns true if a is false. Else returns false

Examples of Logical Operators

  1. #include <stdio.h>
  2.  
  3. int main(void) {
  4. int a = 5, b = 6;
  5. printf("(a == 5) && (b == 7) : %d\n", (a == 5) && (b == 7));
  6. printf("(a == 5) || (b == 7) : %d\n", (a == 5) || (b == 7));
  7. printf("!(a == 5) : %d", !(a == 5));
  8. return 0;
  9. }
  10.  
  11. Output:
  12. (a == 5) && (b == 7) : 0
  13. (a == 5) || (b == 7) : 1
  14. !(a == 5) : 0

No comments: