C-logical operator

www‮ual.‬tturi.com
C-logical operator

We use logical operators to test multiple conditions.

Logical expressions produce nonzero (true) or zero (false) values.

There are three logical operators in C language.

operatormeanings
&&logical AND
||logical OR
logical NOT

logical and

If both operands are nonzero (true), the logical AND and && operators will give a nonzero (true) value.
Otherwise, it returns zero (false).

Truth table for logical AND operator.

ABA && B
000
010
100
111

In the example below, we are checking if both logical expressions are true.
If they are, then we will execute the if block, otherwise the else block.

#include <stdio.h>
int main(void)
{
  int logical_expression_1 = 10 > 0;	//this will give non-zero (true) value
  int logical_expression_2 = 20 <= 100;	//this will give non-zero (true) value
    
  if (logical_expression_1 && logical_expression_2) {
    printf("Success\n");
  }
  else {
    printf("No!!!\n");
  }
  return 0;
}
Success

logical or

If either operand is not zero (true), then the logical or "||" The operator will give a nonzero (true) value.
If both are zero, it returns zero (false).

A truth table of logical or operator values.

ABA || B
000
011
101
111

In the following example, we are checking whether either of the two logical expressions is non-zero (true).
If true, we will execute the if block, otherwise we will execute the else block.

#include <stdio.h>
int main(void)
{
  int logical_expression_1 = 10 > 0;	//this will give non-zero (true) value
  int logical_expression_2 = 20 >= 100;	//this will give zero (false) value
    
  if (logical_expression_1 || logical_expression_2) {
    printf("Success\n");
  }
  else {
    printf("No!!!\n");
  }
  return 0;
}
Success

logical not

If the operand is zero (false), then the logic "! The operator will give a non-zero (true) value.
If the operand is not zero (true), it returns a zero (false) value.

Logical non-operators are used with only one operand.

Truth table for logical NOT operator.

A!A
01
10

example:

#include <stdio.h>
int main(void)
{
  int logical_expression = 10 < 0;	//this will give zero (false) value
    
  if (!logical_expression) {
    printf("Success\n");
  }
  else {
    printf("No!!!\n");
  }
  return 0;
}
Success
Created Time:2017-08-28 06:22:21  Author:lautturi