Logical operators in C, as with other computer languages, are used to evaluate expressions which may be true or false.
Expressions which involve logical operations are evaluated and found to be one of two values: true or false.
If we want to test multiple conditions in the process of making a decision, we have to perform simple tests in separate IF statements.
C provides logical operators that may be used to form more complex conditions by combining simple conditions.
The logical operators in C
Logical Operators | |
Operator | Meaning |
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
Thus logical operators (AND and OR) combine two conditions and logical NOT is used to negate the condition i.e. if the condition is true, NOT negates it to false and vice versa.Let us consider the following examples:
Let us consider the following examples:
(i) Suppose the grade of the student is ‘B’ only if his marks lie within the range 65 to 75, if the condition would be:
if ((marks >=65) && (marks <= 75)) printf (“Grade is B\n”);
(ii) Suppose we want to check that a student is eligible for admission if his PCM is greater than 85% or his aggregate is greater than 90%, then the condition would be, if ((PCM >=85) ||(aggregate >=90))
if ((PCM >=85) ||(aggregate >=90))
printf (“Eligible for admission\n”);
Logical negation (!) enables the programmer to reverse the meaning of the condition. Unlike the && and || operators, which combines two conditions (and are therefore Binary operators), the logical negation operator is a unary operator and has one single condition as an operand. Let us consider an example:
Unlike the && and || operators, which combines two conditions (and are therefore Binary operators), the logical negation operator is a unary operator and has one single condition as an operand. Let us consider an example:
Let us consider an example:
if !(grade==’A’)
printf (“the next grade is %c\n”, grade);
The parentheses around the condition grade==A are needed because the logical operator has higher precedence than equality operator. In a
In a condition, if all the operators are present then the order of evaluation and associativity is provided in the table.
The truth table of the logical AND (&&), OR (||) and NOT (!) are given below.
This table show the possible combinations of zero (false) and nonzero (true) values of x (expression1) and y (expression2) and only one expression in case of NOT operator.
Truth table for AND (&&) operator | ||
A | B | A&&B |
Zero | Zero | 0 |
Non Zero | Zero | 0 |
Zero | Non Zero | 0 |
Non Zero | Non Zero | 1 |
Truth table for OR (||) operator | ||
A | B | A||B |
Zero | Zero | 0 |
Non Zero | Zero | 1 |
Zero | Non Zero | 1 |
Non Zero | Non Zero | 1 |
Truth table for NOT(!) operator | |
A | !A |
Zero | 1 |
Non Zero | 0 |
Logical operators precedence and associativity | |
Operator | Associativity |
! | Right to left |
&& | Left to right |
|| | Left to right |