Jun 9, 2014

C Programming #09: Operators - Logical

Following article will explain logical operators in C.

To understand the logical operators we need to understand binary operators used in mathematics. Binary numbers are 0 and 1, representing false and true respectively.

In C -
  • Zero means false
  • Non zero means true


Logical AND

Logical AND results in true if both of its operands are true, otherwise false. Below is the all possible combination of A and B and their logical AND.

A
B
A AND B
0
0
0
0
1
0
1
0
0
1
1
1

In C '&&' is logical operator.

Logical OR

Logical OR results in true if one or more of its operands are true


A
B
A OR C
0
0
0
0
1
1
1
0
1
1
1
1

In C '||' is logical operator.

Logical NOT

Logical NOT results in true if operand is false and will result in false if operand is true

A Not A
0 1
1 0

In C '!' is NOT operator

Program explaining logical operators

#include <stdio.h>

int main()
{
   int i = 10;
   int j = 1;
   int z = 0;

   printf("i AND j is %d\n", i && j);
   printf("j AND z is %d\n", j && z);
   printf("i AND z is %d\n", i && z);
 
   printf("i OR j is %d\n", i || j);
   printf("j OR z is %d\n", j || z);
   printf("i OR z is %d\n", i || z);
 
 
   printf("NOT of i is %d\n", !i);
   printf("NOT of z is %d\n", !z);
   printf("NOT NOT of i is %d\n", !!i);

   return 0;
}

output of the above program is

i AND j is 1
j AND z is 0
i AND z is 0
i OR j is 1
j OR z is 1
i OR z is 1
NOT of i is 0
NOT of z is 1
NOT NOT of i is 1

NOTE :
  • A && B
    • A and B can be variables/constants/expression. 
    • Expression means combination of variables and constants using operands.
    • But if A is false, we already know that A && B is false regardless of the value of B (see truth table of &&), Hence B is not evaluated at all.
  • A || B
    • If A is true, it is already know that A || B is always true regardless of the value of B  (see truth table of ||), Hence B is not evaluated at all.
  • This concept is called short circuiting. Even though it helps in faster execution but at sometimes confusing and which will lead to lot of software bugs.

Links

Quiz - Not Yet written !!
Next Article -  C Programming #10: Operators - Bit-wise
Previous Article - C Programming #08: Operators - Relational
All Article - C Programming

No comments :

Post a Comment