CodeBlanks Logo Icon CodeBlanks

Logical operators

Learn boolean logic with &&, || and !.

Logical operators

There are three logical operators: && (AND), || (OR) and ! (NOT). They combine true/false values.

int a = 1, b = 0;
int r = a && b;  /* 0: not both true */
int s = a || b;  /* 1: at least one true */
int t = !b;      /* 1: b is false, opposite is true */

The result is again an int: 1 (true) or 0 (false). Logical operators are often used in if conditions.

Short-circuit evaluation

The && and || operators short-circuit. In && if the left side is false the right side is not checked; the result is certainly false. In || if the left side is true the right side is not checked; the result is certainly true.

int x = 0;
if (x != 0 && 10 / x > 1) { /* safe */ }

This is useful to guard against dangerous cases like division by zero. The left condition protects the right side.

Practice Print logical operator results

Define int a = 5, b = 0;. With four printf calls print a && b, a || b, !b and !a on separate lines. Output should be 0, 1, 1, 0.

Starter code

main.c
#include <stdio.h>

int main(void) {
    int a = 5, b = 0;
    /* print a && b, a || b, !b, !a */
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int a = 5, b = 0;
    printf("%d\n", a && b);
    printf("%d\n", a || b);
    printf("%d\n", !b);
    printf("%d\n", !a);
    return 0;
}

Expected output

0
1
1
0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which expression gives 1 (true)?

  • 1 && 0
  • 0 || 0
  • !1
  • 1 && 1 Correct answer

Explanation: 1 && 1 gives 1 because both sides are true.

2 Match logical operators

Term Meaning
&& logical AND
|| logical OR
! not
1 && 1 true

3 Logical AND in a condition

Question
int a = 5, b = 3;
if (a > 0 ____ b > 0) { /* both positive */ }
Answer
int a = 5, b = 3;
if (a > 0 && b > 0) { /* both positive */ }

Explanation: && requires both sides to be true.

All lessons in Beginner