C Reference ยท Operators and Expressions
Logical operators in C
Reference for the C logical operators &&, || and !: how they treat any scalar as true or false, always yield 0 or 1, short-circuit, and differ from & and |.
The logical operators combine or invert conditions. && is logical AND, || is logical OR and ! is logical NOT. In C, any scalar value (integer, floating-point or pointer) can be a condition: zero means false and every other value means true. The result of a logical operator is always the int 1 or 0.
&& and || evaluate their left operand first and skip the right one when the answer is already known. That "short-circuit" behavior is not just an optimization: it is a guarantee you can build code on, such as checking a pointer before using it.
if (p != NULL && p->count > 0) { /* p->count is read only when p is valid */ }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
expr1 && expr2 expr1 || expr2 ! expr
| Operator | Result | Right operand evaluated? |
|---|---|---|
a && b |
1 if both are non-zero, else 0 |
Only if a is non-zero. |
a || b |
1 if either is non-zero, else 0 |
Only if a is zero. |
!a |
1 if a is zero, else 0 |
Not applicable (unary). |
Operands: any scalar types, which are compared against zero (a null pointer counts as zero). The two operands of && or || need not have the same type. Result type: int.
Errors / undefined behavior: there is a sequence point after the left operand of && and ||, so p && p->x and i++ && i are well defined. Operands with no sequence point between them elsewhere remain unsequenced.
Usage notes
- Precedence:
!is a unary operator and binds tightest,&&binds tighter than||, and both are below the comparison operators. Mixed chains are easier to read with parentheses:(a && b) || c. - Short-circuit evaluation protects against null pointers, out-of-range indexes and zero divisors. Put the cheap or guarding test on the left.
- Do not rely on side effects in the right operand: they may not happen.
&&is not&.&and|are bitwise and evaluate both sides;1 & 2is0, while1 && 2is1. See bitwise operators.- Normalizing:
!!xgives1for any non-zerox. In C23,(bool)xdoes the same. - There is no logical XOR operator. Use
!a != !b, or(a != 0) ^ (b != 0). - Alternative spellings
and,or,notexist in<iso646.h>(and are keywords in C++, not in C). - Comparison first:
if (x == 1 || 2)is always true because2is non-zero. Writex == 1 || x == 2. - De Morgan:
!(a && b)equals!a || !b, which is handy for simplifying conditions.