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
| Operator | Means | 5 ? 3 gives |
|---|---|---|
== | equal to | 0 |
!= | not equal to | 1 |
< | less than | 0 |
> | greater than | 1 |
<= | less than or equal | 0 |
>= | greater than or equal | 1 |
Each one gives 1 for true and 0 for false — you can even print it: printf("%d", 5 > 3); prints 1.
Combining: logical operators
| Operator | Means | True when… |
|---|---|---|
&& | AND | both sides are true |
|| | OR | at least one side is true |
! | NOT | the condition is false |
if (age >= 13 && age <= 19) // a teenager
if (day == 6 || day == 7) // the weekend
if (!raining) // not raining
#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
DRun 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:
#include <stdio.h>
int main(void) {
int x = 3;
if (x = 10) {
printf("ten\n");
} else {
printf("not ten\n");
}
return 0;
}output
not tenRun 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?