True and False

Every comparison has an answer: yes or no. Such yes-or-no values are called boolean values, after the mathematician George Boole. In C, their data type is bool, and it has just two values: true and false. To use them, write #include <stdbool.h> at the top of the program, just as you write #include <stdio.h> for printf:

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

int main(void) {
    int age = 20;
    bool is_adult = age >= 18;

    printf("Adult: %d\n", is_adult);
    if (is_adult) {
        printf("You can vote\n");
    }
    return 0;
}

This prints:

Adult: 1
You can vote

Read the line with bool from the right: the program first compares age >= 18, which is true, and then = stores the result in is_adult. The condition if (is_adult) means the same as if (is_adult == true). It's just shorter, which is why programmers write it that way. Names of boolean variables usually start with is_ or has_ (is_adult, has_ticket), so that they read like a yes-or-no question.

Why did printf print 1? For a long time, C had no bool, and underneath it still works with numbers: true is 1 and false is 0. That's why you print a bool with %d. Every comparison gives the number 1 or 0, too:

printf("%d\n", 5 > 3);
printf("%d\n", 2 > 3);

This prints:

1
0

And a condition in C is just a number: 0 means false, and any other number means true. If you forget #include <stdbool.h>, the compiler doesn't know the word bool and reports error: use of undeclared identifier 'bool'.

A boolean variable comes in handy for even numbers, for example. A number is even when nothing is left over after dividing it by two, that is, when the remainder number % 2 is 0:

int number = 14;
bool is_even = number % 2 == 0;

printf("Even: %d\n", is_even);

This prints:

Even: 1

The program first calculates the remainder 14 % 2, which is 0, and only then compares it with zero: % goes before ==, just as multiplication goes before addition. For an odd number, say 7, the remainder is 1 and is_even is false. If you wrote a single equals sign here by mistake, number % 2 = 0, the compiler would report error: expression is not assignable, because you can't store anything in the result of a calculation.

Instructions

Add #include <stdbool.h> at the top of the program. Then, below the printf, create a bool variable is_even holding the result of the comparison number % 2 == 0, and print it: printf("Even: %d\n", is_even);. The number 7 isn't even, so the program prints Even: 0.

Below that line, write an if statement with the condition is_even that prints The number is even, and give it an else branch that prints The number is odd. The program prints:

Number: 7
Even: 0
The number is odd

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

5/12