Skip to content
FollowtheDamnCode

Comparing and Combining Conditions

==, <, >, &&, ||, and !.

5 minute read

Big idea

Relational operators compare two values. Logical operators combine several conditions into one.

Comparing: relational operators

OperatorMeans5 ? 3 gives
==equal to0
!=not equal to1
<less than0
>greater than1
<=less than or equal0
>=greater than or equal1

Each one gives 1 for true and 0 for false — you can even print it: printf("%d", 5 > 3); prints 1.

Combining: logical operators

OperatorMeansTrue when…
&&ANDboth sides are true
||ORat least one side is true
!NOTthe condition is false
if (age >= 13 && age <= 19)   // a teenager
if (day == 6 || day == 7)     // the weekend
if (!raining)                 // not raining
Predict: which lines print?
#include <stdio.h>

int main(void) {
    int a = 5, b = 10;
    if (a > 3 && b > 3) printf("A\n");
    if (a > 7 && b > 7) printf("B\n");
    if (a > 7 || b > 7) printf("C\n");
    if (!(a == b)) printf("D\n");
    return 0;
}
What does it print? Show the answer
A
C
D

Run and edit it in the app.

Short-circuiting

C stops checking as soon as it knows the answer:

  • && stops at the first false — the whole thing can't be true any more.
  • || stops at the first true.

That's useful for guarding: if (count != 0 && total / count > 10) never divides by zero, because when count is 0 the right side never runs.

Watch it

Think of it like

A club with a door rule: "over 18 and on the list". Miss either and you're out. A café's rule is "has a coupon or is a member" — either one gets the discount.

🕷️ Spidey-sense: Swinging needs a building on my left || a building on my right. Landing needs a flat roof && no pigeons. ! pigeons is rare in New York.

Common mistake

= is not ==. One = stores a value; two compare:

Fix the bug: this should print "not ten"
#include <stdio.h>

int main(void) {
    int x = 3;
    if (x = 10) {
        printf("ten\n");
    } else {
        printf("not ten\n");
    }
    return 0;
}
output
not ten

Run and edit it in the app.

x = 10 stores 10 in x, and 10 counts as true — so the wrong branch runs every time.

Key terms

  • Relational operator — Compares two values: ==, !=, <, >, <=, >=.
  • Logical operator — Combines conditions: &&, ||, !.
  • Short-circuit — Stopping early once the result is known.

Check yourself

Which operator checks whether two values are equal?

a = 4, b = 9. What is (a > 5 || b > 5)?

With &&, when does C skip the right side?