C Logical Operators
Logical operators let you combine several true/false conditions into one. For example, you might want to run some code only if a user is logged in AND has permission. C gives you three logical operators to build these kinds of combined tests: AND, OR, and NOT.
The Logical Operators
The three logical operators work with true/false values. Remember that in C, any non-zero value counts as true and 0 counts as false. The result of a logical operator is always 1 or 0.
Using AND and OR
#include <stdio.h>
int main() {
int age = 25;
int hasTicket = 1;
if (age >= 18 && hasTicket) {
printf("You may enter.\n");
}
return 0;
}The message only prints when both conditions are true: the person is at least 18 AND holds a ticket. If either one fails, the whole test is false and nothing prints.
The NOT Operator
The ! operator reverses a condition. If a value is true, ! makes it false, and if it is false, ! makes it true. It is handy for writing checks like only if the user is NOT banned.
Using NOT
#include <stdio.h>
int main() {
int isRaining = 0; // 0 means false
if (!isRaining) {
printf("Let's go outside!\n");
}
return 0;
}- && is true only when both conditions are true.
- || is true when at least one condition is true.
- ! flips a condition from true to false or from false to true.