Learn C · lesson 10 of 60 · about 7 minutes
Logical Operators
Decide whether the backup can run: combine conditions with && (and), || (or) and ! (not).
What you'll learn
- Combine conditions with && and ||
- Flip a condition with !
- Understand short-circuiting
and, or, not
a && bis true only if both are truea || bis true if at least one is true!aflips true to false and false to true
C stops early when it already knows the answer: in a && b, if a is false, b is never checked. This is called short-circuiting.
Combining conditions
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int age = 15;
bool hasTicket = true;
printf("%d\n", age >= 13 && hasTicket);
printf("%d\n", age < 12 || age > 65);
printf("%d\n", !hasTicket);
return 0;
}Output
1
0
0Can the backup run?
Your report's backup needs two things at once: the user typed a size above 0, and at least 512 KiB would still be free. That's backup > 0 && free_kib >= 512. Use brackets when you mix && and ||: && goes first, and gcc warns if you leave them out.
Short-circuiting avoids dividing by zero
#include <stdio.h>
int main(void) {
int people = 0;
int pizza = 8;
printf("%d\n", people != 0 && pizza / people >= 2);
return 0;
}Output
0Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.