ITDeveloper : C Programming
C Programming
Step by Step Tutorials
![]() Share with a Friend |
Logical Operators In C
Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under consideration. They are described below:
- Logical AND operator: The ‘&&’ operator returns true when both the conditions under consideration are satisfied. Otherwise, it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero).
- Logical OR operator: The ‘||’ operator returns true even if one (or both) of the conditions under consideration is satisfied. Otherwise, it returns false. For example, a || b returns true if one of a or b, or both are true (i.e. non-zero). Of course, it returns true when both a and b are true.
- Logical NOT operator: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise, it returns false. For example, !a returns true if a is false, i.e. when a=0.
Examples:
// C program to demonstrate working of logical operators
#include <stdio.h>
int
main()
{
int
a = 10, b = 4, c = 10, d = 20;
// logical operators
// logical AND example
if
(a > b && c == d)
printf
(
"a is greater than b AND c is equal to d\n"
);
else
printf
(
"AND condition not true\n"
);
// logical OR example
if
(a > b || c == d)
printf
(
"a is greater than b OR c is equal to d\n"
);
else
printf
(
"Neither a is greater than b nor c is equal "
" to d\n"
);
// logical NOT example
if
(!a)
printf
(
"a is zero\n"
);
else
printf
(
"a is not zero"
);
return
0;
}
Output:
AND condition not true
a is greater than b OR c is equal to d
a is not zero
In the case of logical AND, the second operand is not evaluated if the first operand is false. For example, the below program doesn’t print “ITDeveloper” as the first operand of logical AND itself is false.
Short-Circuiting in Logical Operators:
In the case of logical AND, the second operand is not evaluated if the first operand is false. For example, the below program doesn’t print “ITDeveloper” as the first operand of logical AND itself is false.
#include <stdbool.h>
#include <stdio.h>
int
main()
{
int
a = 9, b = 5;
bool
res = ((a == b) &&
printf
(
"ITDeveloper"
));
return
0;
}