Logical Operators

The logical operators, shown in Table 1-12, can be used to combine the results of several comparison expressions into one logical expression.

Table 1-12. The logical operators

Operator

Meaning

Example

Result: 1 (true) or 0 (false)

&&

logical AND

x && y

1 if both x and y are not equal to 0

||

logical OR

x || y

1 if either or both of x and y is not equal to 0

!

logical NOT

!x

1 if x equals 0. In all other cases, the expression yields 0.

The operands of logical operators may have any scalar (i. e., arithmetic or pointer) type. Any value except 0 is interpreted as “true”; 0 is “false.”

Like relational expressions, logical expressions yield the values “true” or “false”; that is, the int values 0 or 1:

!x || y  // "(not x) or y" yields 1 (true)
         // if x == 0 or y != 0

The operators && and || first evaluate the left operand. If the result of the operation is already known from the value of the left operand (i. e., the left operand of && is 0 or the left operand of || is not 0), then the right operand is not evaluated. For example:

i < max  &&  scanf("%d", &x) == 1

In this logical expression, the function scanf() is only called if i is less than max.

Get C Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.