Logical Operators

C has three logical operators—AND, OR, and NOT—that allow you to test more than one condition in a single expression. Table 6.6 lists C's logical operators.

Table 6.6 Logical Operators

Operator Description

! Logical NOT
&& Logical AND
| | Logical OR

The logical OR (| |) and AND (&&) operators are often used to combine logical tests within a conditional statement. For example, the if statement

if( val > 10 && sample < 10 )

printf( "Oh joy!\n" );

prints Oh joy! if both conditions in the test expression are true (if val is greater than 10 and sample is less than 10). Here, the relational operators (> and <) have higher “precedence” than the logical AND operator (&&), so the compiler evaluates them first. We discuss operator precedence later in this chapter.

The logical NOT operator (!) reverses an expression's logical value. For instance, if the variable val has the value 8, the expression (val == 8) is true but the expression !(val == 8) is false.

The NOT.C program below shows a common use of this operator.

/* NOT.C: Demonstrate logical NOT operator. */

#include <stdio.h>

main()

{

int val = 0;

if( !val )

printf( "val is zero" );

}

The expression if( !val ) is equivalent to the expression
if( val == 0 )
. When used in this way, the logical NOT operator
converts a 0 value to 1 and any nonzero value to 0.

NOTE:

Don't confuse the logical OR and AND operators with the bitwise OR and AND operators discussed in the previous section. The bitwise operators use the same ASCII symbols, but have only one character. For instance, logical AND is &&, whereas bitwise AND is &.