Logical AND (&&) for combined conditions
What you'll learn: How to use the && operator to ensure two or more conditions are both true before running a piece of code.
The Power of "And"
In programming, you often need to check multiple requirements at once. Imagine you are building a security system for a vault. To open the door, the user must have the correct keycode and the fingerprint scanner must match. If only one of these is true, the door stays shut.
In C, we express this "both must be true" logic using the double ampersand (&&) operator. It sits between two separate expressions and evaluates whether they are both valid.
How it works
Think of the && operator as a strict judge. If the condition on the left is true, the judge then checks the condition on the right. If both are true, the whole statement is considered true. However, if even one side is false, the entire statement fails.
Here is how you might write that in code:
#include <stdio.h>
int main() {
int has_keycode = 1; // 1 represents true
int fingerprint_match = 1; // 1 represents true
// The code inside the { } only runs if BOTH are true
if (has_keycode == 1 && fingerprint_match == 1) {
printf("Access granted. The vault is opening.\n");
} else {
printf("Access denied. Both requirements not met.\n");
}
return 0;
}
Short-Circuiting
C is efficient. If it looks at the first part of an && statement and finds it is false, it doesn't even bother checking the second part. Why? Because the rule of && is that both must be true. If the first half is already false, there is no way for the entire statement to be true, so C stops early to save time. This is known as "short-circuiting."
Using multiple conditions
You aren't limited to just two. You can chain conditions together like a checklist:
if (is_sunny && is_weekend && have_gas).
If any single one of those is false, the result is false. This allows you to create very specific rules for when your code should execute, ensuring all your "ducks are in a row" before proceeding.
Key takeaway
The && operator combines conditions and only returns true if every single part is true.