Building complex logical expressions
What you'll learn: How to combine multiple conditions using AND, OR, and NOT to make sophisticated decisions in your code.
The logic of everyday life
In programming, simple "yes or no" questions often aren't enough. Think about a library: you can borrow a book if you have a library card and you don't have outstanding fines. Or consider a movie theater: you get a discount if you are a student or you are over 65.
In C, we use logical operators to glue these simple true/false questions into complex rules.
The three main tools
We use three primary operators to build these expressions:
- AND (
&&): This is the "all or nothing" operator. The whole expression is true only if every part is true. If one part is false, the whole thing fails. - OR (
||): This is the "flexible" operator. The whole expression is true if at least one part is true. It only fails if everything is false. - NOT (
!): This is the "opposite" operator. It flips true to false and false to true.
Combining them in code
You can stack these operators to handle complex scenarios. C evaluates them in a specific order: it looks at ! first, then &&, and finally ||. However, just like in math, you should use parentheses () to make your meaning clear and ensure the computer groups your conditions exactly how you want.
#include <stdio.h>
int main() {
int age = 20;
int has_ticket = 1; // 1 represents true
int is_banned = 0; // 0 represents false
// To enter the club, you must be 18+ AND have a ticket AND NOT be banned
if (age >= 18 && has_ticket && !is_banned) {
printf("Welcome to the club!\n");
}
// You get a free drink if you are the "Guest of Honor" OR it is your birthday
int is_guest_of_honor = 0;
int is_birthday = 1;
if (is_guest_of_honor || is_birthday) {
printf("Here is your free drink!\n");
}
return 0;
}
Reading the expression
When you see (A && B) || C, read it as a story: "The result is true if both A and B happen, OR if C happens on its own." By nesting these logical bricks, you can teach your program to navigate any real-world situation, no matter how many rules are involved.
Key takeaway
Use && (AND), || (OR), and ! (NOT) with parentheses to chain simple true/false facts into powerful decision-making rules.