Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. Basics of C Programming
  5. Expressions
  6. Logical operators

Logical operators

Logical operators are used to logically relate the sub expression

  • In C, there is no operator for Exclusive or (XOR)
  • Logical operators work according to the truth table
  • If an operand of a logical operator is a non-zero value, the operand is considered as true. If the operand is zero, it is false
  • Each of the logical operator yields 1, if the specified condition evaluates to True

The logical operators are listed as,

The truth table are given as,

AND Operator

OR Operator

NOT Operator

Example

Illustration of Logical operator

#include<stdio.h>
int main()
{
	int i = 0, j = 1, k = 2, res;
	res = i && j++ && k++;
	printf("i=%d,j=%d,k=%d,res=%d",i,j,k,res);
	return 0;
}

Output

i=0,j=1,k=2,res=0

Explanation

  • i is 0 therefore j++ is not executed.
  • Similarly k ++ is not executed and 0 is assigned to res

Illustration of Logical operator

#include<stdio.h>
int main()
{
	int i = 0, j = 1, k = 2, res;
	res = i && j++ || k++;
	printf("i=%d,j=%d,k=%d,res=%d",i,j,k,res);
	return 0;
}

Output

i=0,j=1,k=3,res=1

Explanation

  • i is 0 therefore j++ is not executed. Because of the use of ||
  • k++ is evaluatedres = 0||2 is executed and then k = k+1 executes

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments