Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 135 ยท Operators

Comparison and Logical Operators

Learn C's relational and logical operators: 0 and 1 results, short-circuit && and ||, signed vs unsigned traps, comparing floats safely, and comparing pointers.

Every decision a program makes starts with a question: is the balance large enough, did the user type q, is the pointer valid, has the loop reached the end? In C you ask these questions with the six comparison (relational and equality) operators, and you combine the answers with the three logical operators &&, || and !.

C's version of these operators has a few traits you won't find in every language. There was no boolean type at all until C99, so comparisons produce plain int values. && and || stop evaluating as soon as the answer is known, which is a feature you'll use constantly. And comparing a negative number with an unsigned one, or two floating-point results, can give answers that look wrong until you know the rules.

The six comparison operators

Operator Meaning 7 ? 3 gives
a == b equal to 0
a != b not equal to 1
a < b less than 0
a > b greater than 1
a <= b less than or equal to 0
a >= b greater than or equal to 1

Each comparison produces an int: 1 when it's true and 0 when it's false. Even in C23, where bool, true and false are keywords (see Booleans), the result of a < b still has type int. The other direction is broader: wherever C expects a condition, such as in if or while, any nonzero value counts as true and only zero counts as false.

C Comparisons produce 0 or 1

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.

Because the results are numbers, you can add them up, as the passed line does. Characters compare by their codes, so 'A' < 'B' and '0' < '9' are true, but 'a' < 'B' is false in ASCII, where all uppercase letters come before lowercase ones (see Characters and ASCII).

== is not =

The equality operator has two equal signs. if (x = 0) assigns zero and is therefore never true; GCC warns about it, and the if, else if and else lesson shows how to avoid it for good.

a < b < c doesn't mean what it says

In math, 1 < x < 10 checks a range. In C, the comparisons group left to right, so 1 < x < 10 means (1 < x) < 10. The inner comparison gives 0 or 1, and both are less than 10, so the whole expression is always true. GCC warns: comparisons like 'X<=Y<=Z' do not have their mathematical meaning. Write 1 < x && x < 10 instead.

Logical operators: &&, || and !

Operator Name True (1) whenโ€ฆ
a && b logical AND both a and b are nonzero
a || b logical OR at least one of a and b is nonzero
!a logical NOT a is zero

Like comparisons, they always produce int 0 or 1. That gives you the idiom !!x, which turns any value into exactly 0 or 1.

! binds very tightly, more tightly than any comparison, so !x == y means (!x) == y. When you want to negate a comparison, use parentheses (!(x == y)) or simply the opposite operator (x != y).

De Morgan's laws help you simplify negated conditions:

C
!(a && b)   is the same as   !a || !b
!(a || b)   is the same as   !a && !b

// "not a weekend day" two ways:
!(day == SATURDAY || day == SUNDAY)
day != SATURDAY && day != SUNDAY

Short-circuit evaluation

&& and || evaluate their left operand first, and evaluate the right operand only if it can still change the result:

  • In a && b, if a is false the result is already false, so b is skipped.
  • In a || b, if a is true the result is already true, so b is skipped.

The left side is also completely finished, including its side effects, before the right side starts. This makes short-circuiting a guarantee you can build on, most often as a guard: the left side checks that the right side is safe.

C Short-circuit guards

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.

In each guard, swapping the two sides would be a real bug: a division by zero, a null pointer dereference or an out-of-bounds read, all undefined behavior. The order of operands in && and || is part of your program's logic.

Don't put side effects you depend on in the right operand. In if (ready && count++ > 3), count is incremented only when ready is true. If the increment must always happen, do it in its own statement.

Mixing && and ||

&& has higher precedence than ||, so a || b && c means a || (b && c). That's easy to misread, and GCC with -Wall asks you to suggest parentheses around '&&' within '||'. Add the parentheses even when the default grouping is the one you want.

& and | are not && and ||

The single-character operators & and | are bitwise operators. They compare every bit and never short-circuit, so p != NULL & *p > 0 still dereferences a null pointer. They also give different answers: 2 & 1 is 0 (no bits in common), while 2 && 1 is 1 (both nonzero). Use the doubled forms for conditions.

Signed versus unsigned: when -1 is not less than 1

When you compare an int with an unsigned int, the usual arithmetic conversions turn the int into unsigned. A negative value such as -1 becomes the largest unsigned value, 4,294,967,295 on our server, so it compares as greater than every small unsigned number. The trap appears most often with size_t lengths, because sizeof and strlen return unsigned values. This example compiles with a warning on purpose:

C Comparing signed and unsigned values

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.

GCC's -Wextra reports comparison of integer expressions of different signedness: 'int' and 'unsigned int'. Treat that warning as an error in your own code. The fix is either to check for negative values first, as above, or to give both values the same type from the start. Type Conversions and Casts explains the full rules.

Comparing floating-point numbers

Floating-point numbers are stored in binary with limited precision, so many decimal fractions can't be represented exactly. After a few calculations, two results that are equal on paper are often slightly different in memory, and == reports false.

The usual fix is to compare with a tolerance: consider two values equal if they differ by less than some small amount. A fixed tolerance like 1e-9 works for numbers near 1; for values that may be very large or very small, scale the tolerance by the size of the numbers (a relative tolerance).

There's one more special case: NaN (not a number, for example 0.0 / 0.0) compares unequal to everything, including itself. x != x is true only for NaN, but the readable test is isnan(x) from <math.h>.

C Why == fails for floating-point results

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.

0.1 + 0.2 prints as 0.30000000000000004, which is why sum == 0.3 is 0. The 1e20 line shows why the tolerance is relative: near 1e20, neighboring double values are about 16,000 apart, so a fixed tolerance like 1e-9 would be meaningless there, while one scaled by the size of the numbers treats the two values as equal. Comparisons such as < and > are fine with floating-point values, as long as you remember that "just below" and "just above" may differ from what decimal arithmetic suggests. Floating-Point Numbers explains where these errors come from.

Comparing pointers and strings

You'll study pointers later in the course, but two rules belong here:

  • == and != work for any two pointers of compatible type and for comparisons with NULL (or nullptr in C23). if (p != NULL) and its short form if (p) are everywhere in C code.
  • <, >, <= and >= are only defined for pointers into the same array (or one past its end). Comparing addresses of unrelated variables is undefined. Pointer Arithmetic covers this.

Strings are the trap here. A string in C is an array of characters, and name == "admin" compares two addresses, not the text. It may be false even when the text matches. Compare string contents with strcmp from <string.h>, which returns 0 when the strings are equal:

C
if (strcmp(name, "admin") == 0) {
    // the text matches
}

The String Functions lesson explains strcmp and its relatives.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does printf("%d", (5 > 3) + (2 > 4) + (1 == 1)); print?

    Each comparison produces an int, 1 for true and 0 for false, so the sum is 1 + 0 + 1.
  2. 2. With int x = 50;, what is the value of 1 < x < 10?

    The expression is parsed as (1 < x) < 10. The inner part is 0 or 1, both less than 10, so the result is always 1. Write 1 < x && x < 10.
  3. 3. In if (p != NULL && p->count > 0), what happens when p is NULL?

    && evaluates its left operand first and skips the right one when the left is false. That ordering is guaranteed.
  4. 4. With int a = -1; unsigned int b = 1;, what is a < b?

    The usual arithmetic conversions turn a into unsigned int, where -1 becomes UINT_MAX. GCC warns about the comparison with -Wextra.
  5. 5. Which is the right way to check that the string in name is "quit"?

    == compares addresses, not text. strcmp returns 0 for equal strings, so the plain strcmp(...) condition is true when they differ.

Summary

  • == != < > <= >= produce an int: 1 for true, 0 for false. Any nonzero value counts as true in a condition.
  • a < b < c doesn't check a range; write a < b && b < c. Don't confuse == with =.
  • && and || short-circuit: the left side is evaluated first, and the right side only if needed. Use that to guard divisions, pointers and array indexes.
  • ! binds tightly; && binds tighter than ||. Add parentheses when you mix them.
  • Comparing signed with unsigned converts the signed value: -1 < 1u is false. Heed -Wextra's signedness warning.
  • Compare floating-point results with a tolerance, and test for NaN with isnan.
  • Compare pointers with ==/!= (ordering only within one array) and strings with strcmp, never ==.

Next: Bitwise Operators