Course contentsShow
← C
Lesson 168 of 1,2193. Operators and ExpressionsFree lesson

Logical AND `&&`

Logical AND &&

What you'll learn: How to use the && operator to check if two conditions are both true at the same time.

The Double-Check

In programming, we often need to satisfy more than one requirement before taking an action. Imagine you are at a movie theater. To get a student discount, you need two things: you must be under 25 and you must have a valid ID. If you have only one of those, you pay full price.

In C, we represent this "and" logic using two ampersands: &&.

The && operator sits between two expressions. It looks at the left side and the right side. If both sides are true, the entire expression results in 1 (true). If even one side is false, the whole thing results in 0 (false).

How it works in code

Think of && as a strict judge. It only gives a thumbs up if every condition presented is met.

#include <stdio.h>

int main() {
    int age = 20;
    int hasID = 1; // 1 represents true in C

    // Check if the person is under 25 AND has an ID
    if (age < 25 && hasID == 1) {
        printf("Discount applied!\n");
    } else {
        printf("Full price ticket.\n");
    }

    return 0;
}

In this example, the computer first checks age < 25. Since 20 is less than 25, that part is true. Then it checks hasID == 1. That is also true. Because both sides are true, the message "Discount applied!" prints. If we changed age to 30, the first condition would fail, making the entire && expression false.

The "Short-Circuit" Feature

C is efficient. When using &&, it reads from left to right. If the first condition is false, C doesn't even bother looking at the second condition. Why? Because no matter what the second condition is, the "AND" requirement can no longer be satisfied. This is called "short-circuiting," and it helps your programs run just a little bit faster.

Key takeaway

The && operator returns true only if the expressions on both sides are true; if either side is false, the result is false.