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

Precedence of logical operators

Precedence of logical operators

What you'll learn: How C decides the order of operations when multiple logical conditions like AND and OR are used in the same expression.

The Hierarchy of Logic

In C programming, logical operators follow a strict "pecking order" similar to the order of operations in math (PEMDAS). When you mix ! (NOT), && (AND), and || (OR) in a single line of code, C doesn't just read from left to right. Instead, it follows a specific ranking:

  1. Logical NOT (!): Highest precedence. It happens first.
  2. Logical AND (&&): Middle precedence.
  3. Logical OR (||): Lowest precedence. It happens last.

Think of it like a sentence in English: "I will go outside if it is not raining and I have an umbrella, or if I have a waterproof suit." The "not" applies to the rain immediately, the "and" binds the umbrella to the rain status, and the "or" acts as a final backup option.

The "AND" vs "OR" Trap

A common mistake is assuming that && and || are equal. They are not. In C, && is like multiplication, while || is like addition. Just as 2 + 3 * 4 equals 14 (because multiplication happens first), an expression with both operators will evaluate the && pairs before checking the || conditions.

If you want to change this order, you must use parentheses () to force C to look at a specific part first.

#include <stdio.h>

int main() {
    int hasTicket = 0;    // False
    int isVip = 1;        // True
    int hasBackstagePass = 1; // True

    // Without parentheses: && is evaluated before ||
    // Logic: hasTicket OR (isVip AND hasBackstagePass)
    // Result: 0 || (1 && 1) -> 0 || 1 -> 1 (True)
    if (hasTicket || isVip && hasBackstagePass) {
        printf("Access granted!\n");
    }

    // With parentheses: We force || to happen first
    // Logic: (hasTicket OR isVip) AND hasBackstagePass
    if ((hasTicket || isVip) && hasBackstagePass) {
        printf("This also works, but the order is forced.\n");
    }

    return 0;
}

Why This Matters

When building complex logic—like checking if a user is logged in, has the right permissions, or is an administrator—forgetting precedence can lead to security holes. If you aren't 100% sure how the compiler will rank your operators, always use parentheses. It makes your code safer and much easier for other humans to read.

Key takeaway

Logical NOT happens first, followed by AND, and finally OR; use parentheses to override this order.