We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Logical Operators

Logical operators let you combine multiple conditions in C. There are three main logical operators you'll use all the time:

  • && – Logical AND: true if both conditions are true
  • || – Logical OR: true if either condition is true
  • ! – Logical NOT: inverts a boolean value
int age = 25;
bool has_license = true;

if (age >= 18 && has_license) {
    printf("Can drive\n");
}

Short-Circuit Evaluation

C uses short-circuit evaluation with logical operators. This means:

  • With &&, if the first condition is false, the second isn't even checked (because the whole thing is already false)
  • With ||, if the first condition is true, the second isn't checked (because the whole thing is already true)
if (x != 0 && 10 / x > 2) {
    // The division only happens if x != 0
    // This prevents a division by zero error
    printf("Safe!\n");
}

Operator Precedence

Logical NOT (!) has higher precedence than AND (&&), which has higher precedence than OR (||). When in doubt, use parentheses to make your intent crystal clear:

// without parentheses – might be confusing
if (!is_raining && is_sunny || is_weekend)

// with parentheses – much clearer
if ((!is_raining && is_sunny) || is_weekend)

Assignment

The Sneklang package manager needs an access control system for its private package registry. Take a look at exercise.h and implement the function in exercise.c.

The can_access_registry function should return 1 (true) if a user can access the private registry, or 0 (false) if they cannot.

A user can access the private registry if any of these conditions are met:

In C, we use 1 for true and 0 for false when returning boolean-like values from functions that return int.