🎓 A1Learner
🔍
0 of 50 lessons completed

C Comparison Operators

A comparison operator tests two values and answers true or false. A switch matched exact values; a comparison also tests ranges, like larger than or equal to.

Equal or not

Age is 20, so the check age != 18 is true. The first block runs and prints Not eighteen.

#include <stdio.h>

int main() {
  int age = 20;
  if (age != 18) {
    printf("Not eighteen.\n");
  } else {
    printf("Eighteen.\n");
  }
  return 0;
}

Two checks joined

Score is 75, so both parts of the joined check are true. The first block runs and prints Good score.

#include <stdio.h>

int main() {
  int score = 75;
  if (score > 50 && score < 90) {
    printf("Good score.\n");
  } else {
    printf("Out of range.\n");
  }
  return 0;
}

Single equals sign

Age starts at 20, then a single = gives it 18 instead of testing it. The test reads the new value 18 as true, so the wrong line prints.

#include <stdio.h>
#include <stdbool.h>

int main() {
  int age = 20;
  bool adult = (age = 18);
  if (adult) {
    printf("Eighteen.\n");
  } else {
    printf("Not eighteen.\n");
  }
  return 0;
}

Example

#include <stdio.h>

int main() {
  int day = 6;
  if (day == 6 || day == 7) {
    printf("Weekend.\n");
  } else {
    printf("Weekday.\n");
  }
  return 0;
}

Key points

  • == asks whether two values are the same.
  • != asks whether two values differ.
  • < checks whether the left value is smaller than the right value.
  • > checks whether the left value is larger than the right value.
  • The answer is always a bool value, true or false.
  • && joins two checks, and the whole check is true only when both parts are true.
  • || joins two checks, and the whole check is true when at least one part is true.
  • An if check uses a comparison to choose between blocks.

Day is 6, so the first part of the check is true and the whole check is true. The if block runs and prints Weekend.

Note

== has two equals signs, and a single = gives a value instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line checks whether age equals 18?