2.1 Relational and Logical Operators
Programs do not only run statements in order. They often need to check whether a condition holds, then choose what to do next. In C, a condition’s result is an integer: 0 means false, and any nonzero value means true.
Relational operators
Relational operators compare two values. The result is 1 (true) or 0 (false), not another number.
Common C relational operators:
<: less than>: greater than<=: less than or equal to>=: greater than or equal to==: equal to!=: not equal to
Important: one equals sign = means assignment. Two equals signs == mean comparison.
int age = 17;
printf("%d\n", age < 18); // 1
printf("%d\n", age == 18); // 0
printf("%d\n", age != 18); // 1age = 17 stores 17 in the variable age. age == 18 checks whether the current value of age equals 18.
Logical operators
Logical operators combine multiple conditions. Their result is still 1 or 0.
&&: the whole expression is true only when every condition is true.||: the whole expression is true when at least one condition is true.!: turns true into false, and false into true.
Truth tables
A truth table lists every possible input combination to make the rules clear.
&& is true only when both sides are true.
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
|| is true when at least one side is true.
| A | B | A `\ | \ | ` B |
|---|---|---|---|---|
| true | true | true | ||
| true | false | true | ||
| false | true | true | ||
| false | false | false |
! acts on a single value and flips the result.
| A | ! A |
|---|---|
| true | false |
| false | true |
int age = 20;
int has_ticket = 1;
printf("%d\n", age >= 18 && has_ticket); // 1
printf("%d\n", age < 18 || has_ticket); // 1
printf("%d\n", !has_ticket); // 0It helps to read conditions like plain language: age >= 18 && has_ticket means “the age is at least 18, and the person has a ticket.”
Combining conditions
Unlike math notation, C does not support chaining comparisons. 0 < age < 18 does not cause an error in C, but it does not mean “age is between 0 and 18,” so write it as two conditions joined by &&.
int age = 16;
printf("%d\n", 0 < age && age < 18); // 1When a condition becomes complex, name each smaller condition first, then combine them.
int score = 85;
int attendance = 92;
int passed = score >= 60 && attendance >= 80;
int excellent = score >= 90 || attendance >= 95;
printf("%d\n", passed); // 1
printf("%d\n", excellent); // 0Do not rush to squeeze every condition into one line. Naming smaller conditions makes the program easier to read and debug.