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.
|
Operator |
Meaning |
Example |
Result: 1 (true) or 0 (false) |
&& |
logical |
x && y |
|
|| |
logical |
x || y |
|
! |
logical |
!x |
|
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 != 0The 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) == 1In this logical expression, the function scanf()
is only called if i is less than
max.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access