C Logic operators
Syntax
Character Set | Boolean Operator |
---|---|
&& | and |
|| | or |
! | Not |
AND
&&
operator: evaluate a Boolean expression from left to right.
Both sides of the operator must evaluate to true before the entire expression becomes true.
OR
|| operator: evaluate from left to right. If either side of the condition is true, the whole expression results in true.
NOT
The ! operator is a unary operator, because it applies to just one operand.
The logical NOT operator reverses the value of a logical expression: true becomes false, and false becomes true.
Example
You can combine multiple relations or logical operations by logical operation.
The logical operators are negation (!
), logical AND (&&
),
and logical OR (||
).
#include<stdio.h>
/*from w w w . j a v a 2 s. c o m*/
main(){
int c1 = 1,c2 = 2,c3 = 3;
if((c1 < c2) && (c1<c3)){
printf("\n c1 is less than c2 and c3");
}
if (!(c1< c2)){
printf("\n c1 is greater than c2");
}
if ((c1 < c2)||(c1 < c3)){
printf("\n c1 is less than c2 or c3 or both");
}
}
The code above generates the following result.
Logical operators AND, and OR have higher priority than assignment operators. Logical operators AND, and OR have lower priority than relational operators. Negation operators have the same priority as unary operators.
Short circuiting
When evaluating logical expressions, C uses the technique of short circuiting.
C1 && C2 && C3 && C4
So if C1 is false C2, C3, and C4 are not evaluated.
C1 || C2 || C3 || C4
So if C1 is true C2, C3, and C4 are not evaluated.