Relational & Logical Operators

Relational & Logical Operators in C: A bouncer on the door has a list of conditions: old enough, on the guest list, not already inside, dressed to code.

The Analogy: The Bouncer's Checklist

A bouncer on the door has a list of conditions: old enough, on the guest list, not already inside, dressed to code. Each item is a yes-or-no question, and the door opens only if the answers combine the right way.

C works the same way, with one twist that catches almost everyone: C has no built-in true and false keywords in its original form. Instead, 0 means false and literally every other value means true. The number 42 is true. The number -1 is true. The character 'a' is true. Only zero is false.

The second half of the twist is that comparisons in C do not hand back some special boolean type. They hand back a plain int — exactly 1 for true and exactly 0 for false. That is why printf("%d", 3 > 2) prints 1. Once you accept that conditions are just integers, a great deal of otherwise mysterious C code becomes readable.

Since C99 you can #include <stdbool.h> and write bool, true and false. It is a thin layer of names over the same integers, and it is worth using purely because it tells the next reader what you meant.


Syntax or Core Structure

Six relational operators ask a question about two values. Three logical operators combine the answers.

#include <stdio.h>

int main(void) {
    int age = 20, credits = 3;

    printf("age > 18       -> %d\n", age > 18);
    printf("age == 20      -> %d\n", age == 20);
    printf("age != 20      -> %d\n", age != 20);
    printf("credits >= 5   -> %d\n", credits >= 5);

    printf("both           -> %d\n", age > 18 && credits >= 5);
    printf("either         -> %d\n", age > 18 || credits >= 5);
    printf("negated        -> %d\n", !(age > 18));

    return 0;
}

Output:

age > 18       -> 1
age == 20      -> 1
age != 20      -> 0
credits >= 5   -> 0
both           -> 0
either         -> 1
negated        -> 0
OperatorQuestion it asksNote
==are these equal?two equals signs, always
!=are these different?
< >strictly less, strictly greater
<= >=less or equal, greater or equalno spaces between the symbols
&&are both sides true?short-circuits
`\\`is either side true?short-circuits
!flip this truth valuebinds very tightly

Technical Depth: Short-Circuiting, Precedence and Equality Traps

Short-circuit evaluation is a guarantee, not an optimisation

&& evaluates its left side first. If that side is false, the right side is never evaluated at all — not called, not computed, nothing. || mirrors it: if the left side is true, the right side is skipped. The standard requires this, so you can rely on it for safety.

#include <stdio.h>

int noisy(int value) {
    printf("  [noisy(%d) ran]\n", value);
    return value;
}

int main(void) {
    printf("0 && noisy(1):\n");
    int a = 0 && noisy(1);

    printf("1 || noisy(2):\n");
    int b = 1 || noisy(2);

    printf("1 && noisy(3):\n");
    int c = 1 && noisy(3);

    printf("a=%d b=%d c=%d\n", a, b, c);
    return 0;
}

Output:

0 && noisy(1):
1 || noisy(2):
1 && noisy(3):
  [noisy(3) ran]
a=0 b=1 c=1

Only one of the three calls happened. This is what makes the classic C guard idiom safe:

if (p != NULL && p->count > 0) { /* ... */ }
if (i < length && data[i] == target) { /* ... */ }
if (divisor != 0 && total / divisor > 10) { /* ... */ }

In each case the left side protects the right side, and the order is not negotiable. Swap them and you have a crash instead of a check.

Precedence: from tightest to loosest

BindsOperators
tightest! and other unary operators
* / %
+ -
< <= > >=
== !=
&&
loosest`\\`

Two consequences follow. First, arithmetic always happens before comparison, so a + 1 < b needs no parentheses. Second, && binds tighter than ||, so x || y && z means x || (y && z). Write the parentheses anyway.

Three equality traps

Chained comparisons do not mean what they say. if (3 < x && x < 10) is the correct form. if (3 < x < 10) compiles, but it parses as (3 < x) < 10, which is 0 < 10 or 1 < 10 — always true, for every value of x.

== on floating point is almost always wrong.

#include <stdio.h>
#include <math.h>

int main(void) {
    double sum = 0.1 + 0.2;
    printf("sum == 0.3          -> %d\n", sum == 0.3);
    printf("sum printed exactly -> %.17f\n", sum);
    printf("close enough        -> %d\n", fabs(sum - 0.3) < 1e-9);
    return 0;
}

Output:

sum == 0.3          -> 0
sum printed exactly -> 0.30000000000000004
close enough        -> 1

Binary floating point cannot represent 0.1 exactly, so the sum lands a hair above 0.3. Compare with a tolerance instead, and remember to link with -lm when you use <math.h>.

== on strings compares addresses, not letters. name == "Ada" asks whether two pointers point at the same memory, which is almost never what you meant. Use strcmp(name, "Ada") == 0 — and note the awkward part: strcmp returns zero when the strings match, so equality reads as false-looking code.

What counts as true, compared with languages you know

ValueC treats it asPythonJavaScript
0falsefalsefalse
0.0falsefalsefalse
-1truetruetrue
an empty stringtrue — it is a valid pointerfalsefalse
a NULL pointerfalsen/afalsy
an empty arraytrue — it is an addressfalsetrue

The empty-string row is the one that bites people arriving from Python. if (name) in C asks "is this pointer non-null", not "does this string have characters in it". For the second question you want if (name[0] != '\0').

Signed against unsigned

int i = -1;
unsigned int u = 1;
printf("%d\n", i < u);     /* prints 0, not 1 */

Before comparing, C converts both operands to a common type, and unsigned int wins over int. So -1 becomes 4294967295, which is not less than 1. -Wall -Wextra warns about this; take the warning seriously.


Real World Example: A Validation Gate

Almost every real program has one function like this: a single expression that decides whether some input is acceptable. Short-circuiting is what makes it both safe and readable.

#include <stdio.h>
#include <string.h>

#define MIN_AGE   13
#define MAX_NAME  32

int is_valid_signup(const char *name, int age, int accepted_terms) {
    return name != NULL                /* must exist before we touch it */
        && name[0] != '\0'             /* must not be empty            */
        && strlen(name) < MAX_NAME      /* must fit our column          */
        && age >= MIN_AGE
        && accepted_terms;
}

int main(void) {
    printf("Ada, 30, agreed   -> %d\n", is_valid_signup("Ada", 30, 1));
    printf("empty name        -> %d\n", is_valid_signup("", 30, 1));
    printf("too young         -> %d\n", is_valid_signup("Ada", 9, 1));
    printf("no name at all    -> %d\n", is_valid_signup(NULL, 30, 1));
    printf("terms not agreed  -> %d\n", is_valid_signup("Ada", 30, 0));
    return 0;
}

Output:

Ada, 30, agreed   -> 1
empty name        -> 0
too young         -> 0
no name at all    -> 0
terms not agreed  -> 0

The clause order is the entire design of that function:

  • name != NULL comes first because every clause after it dereferences name. Move it later and the NULL case becomes a segmentation fault.
  • name[0] != '\0' comes before strlen, because reading one byte is cheaper than walking the whole string.
  • accepted_terms is used directly. It is an int acting as a flag, and && accepted_terms reads better than && accepted_terms != 0. Both are correct.

Common Mistakes

  1. = where == belongs. if (status = 0) assigns zero and is always false. if (0 == status) — the so-called Yoda form — makes the typo a compile error.
  2. Chaining comparisons. if (0 <= i < n) is always true. Write if (0 <= i && i < n).
  3. Comparing floating-point values with ==. Use fabs(a - b) < tolerance, with a tolerance scaled to the size of the numbers involved.
  4. Comparing strings with ==. That compares two addresses. Use strcmp, and remember it returns 0 on a match.
  5. Putting the guard second. if (p->count > 0 && p != NULL) dereferences p before checking it. Short-circuiting only helps when the protective test is on the left.
  6. Relying on a side effect that gets short-circuited away. In if (cached || load_from_disk()), the load silently never happens once cached is true. Keep function calls with side effects out of conditions.
  7. Typing & for && or | for ||. The bitwise versions compile, evaluate both sides, and give different answers: 2 && 1 is 1 but 2 & 1 is 0.
  8. Comparing a signed value with an unsigned one. The signed operand is converted, negative numbers become enormous, and the test quietly inverts.

Best Practices

  • #include <stdbool.h> and declare flags as bool. It costs nothing and states your intent.
  • Order the clauses of && so the protective and the cheap tests come first.
  • Compare floating-point values against a tolerance, never for exact equality.
  • Wrap repeated strcmp(a, b) == 0 in a small named helper such as streq, so the reader is not decoding the zero every time.
  • Parenthesise any condition that mixes && with ||, even when precedence is already on your side.
  • Move any condition longer than about two clauses into a named predicate function. if (is_valid_signup(...)) documents itself.
  • Keep both sides of a comparison the same signedness, and let -Wall -Wextra police it.
  • Use bare truthiness (if (p)) for pointers and bool values only. For counters, write the comparison out: if (count != 0).

Practice Exercises

  1. Leap years. Write int is_leap(int year) using only &&, || and %: a year is a leap year if it is divisible by 4 and not by 100, or if it is divisible by 400. Confirm it returns 0 for 1900, 1 for 2000, 1 for 2024 and 0 for 2023.
  2. The chaining bug, demonstrated. Print the value of 3 < x < 10 and of 3 < x && x < 10 for x equal to 1, 5 and 50. Write one sentence explaining why the first column is identical in all three rows.
  3. Tolerant equality. Write int nearly_equal(double a, double b, double eps) and use it to show that 0.1 + 0.2 is not exactly 0.3 but is equal within 1e-9. Then find a pair of very large numbers where a fixed tolerance of 1e-9 is too strict to be useful.
  4. Password gate. Write a predicate that accepts a string only if it is at least 8 characters long, contains at least one digit and at least one uppercase letter. Use short-circuiting so that a NULL password returns 0 without ever being indexed, and make sure your scan stops at the terminating '\0'.