Step 3 of 6
And, or, not
Often a decision depends on more than one thing. Logical operators combine conditions:
| Operator | Name | True when |
|---|---|---|
a && b |
and | both a and b are true |
a || b |
or | at least one is true |
!a |
not | a is false |
#include <stdio.h>
int main(void) {
int age, has_ticket;
scanf("%d %d", &age, &has_ticket);
if (age >= 18 && has_ticket) {
printf("welcome\n");
}
if (age < 18 || !has_ticket) {
printf("sorry\n");
}
return 0;
}
20 0
sorry
Truth in C
C has no special true/false type in its oldest form: any non-zero number counts as true, and 0 is false. That's why has_ticket alone works as a condition, and !has_ticket is true when it's 0. (Modern C also has bool, true and false from <stdbool.h>; they're 1 and 0 underneath.)
Short-circuiting
&& stops as soon as the left side is false, and || stops as soon as the left side is true, because the answer is already known. This is useful for safety checks: in count > 0 && total / count > 10, the division only happens when count isn't zero.
Precedence
! binds tightest, then comparisons, then &&, then ||. So a || b && c means a || (b && c). Use parentheses when you mix && and ||, even when you know the rules; the next reader might not.
Your turn: read money and round (two ints). A player can buy if they have at least 2700 money and it is not the first round (round 1 is a pistol round). Print buy or save.