DMarlon Studio

Lesson 7 · 7 of 20

Comparison and logic · C

Compare values in C with ==, !=, < and >=, and combine conditions with &&, || and !. True is 1 and false is 0; plus the ?: ternary operator.

C · Comparison and logic in DMarlon Studio: the example's code and its output in the terminal

In its most basic form, C has no special type for true and false: 0 is false and any other number is true. That is why a comparison such as age == 15 gives 1 when it holds and 0 when it does not, as the first three lines of output show.

The comparison operators are == (equal), != (not equal), <, >, <= and >=. Do not mix up `==`, which compares, with =, which assigns: if (lives = 0) would store 0 in lives and the condition would always be false.

To combine conditions there is `&&` (and), which needs both to hold, `||` (or), which is happy with one, and `!` (not), which flips the result. With has_ticket set to 1 and a height of 1.42 metres you can ride the roller coaster; at 15 there is no reduced price, and !has_ticket is false, so no ticket is asked for.

age >= 13 && age <= 17 checks a range, and its result (1) can be stored in a variable. The ternary operator teen ? "yes" : "no" picks one value or the other depending on the condition, which is very handy inside printf.

Code · main.c

#include <stdio.h>int main(void) {    int age = 15;    int has_ticket = 1;  // in C, 0 is false and any other number is true    double height = 1.42;    // A comparison gives 1 (true) or 0 (false).    printf("age == 15: %d\n", age == 15);    printf("age != 18: %d\n", age != 18);    printf("age >= 18: %d\n", age >= 18);    // && (and): both sides must be true.    if (has_ticket && height >= 1.40) {        printf("You can ride the roller coaster.\n");    }    // || (or): at least one side must be true.    if (age < 12 || age >= 65) {        printf("Reduced price.\n");    } else {        printf("Full price.\n");    }    // ! (not) turns true into false and false into true.    if (!has_ticket) printf("Buy a ticket first.\n");    // A range: from 13 to 17, both included.    int teen = age >= 13 && age <= 17;    // condition ? a : b picks a when true, b when false.    printf("Teenager? %s\n", teen ? "yes" : "no");    // Remember: = assigns a value, == compares two values.    int lives = 0;    if (lives == 0) printf("Game over.\n");    return 0;}

Output · cc main.c -o main && ./main

age == 15: 1
age != 18: 1
age >= 18: 0
You can ride the roller coaster.
Full price.
Teenager? yes
Game over.

Key points

  • In C, 0 is false and any other value is true.
  • == compares; = assigns.
  • && needs both conditions; || needs at least one.
  • ! flips a condition.
  • c ? a : b gives a when c is true, b otherwise.

Exercise

Add a with_adult variable and let riders on if they are at least 1.20 metres tall with an adult, or 1.40 on their own, in a single condition using && and ||.