Menu
CoddyTech

Booleans

Part of the Fundamentals section of Coddy's C journey. Lesson 9 of 63.

The first versions of C had no boolean data type like other languages, so C uses integers to represent boolean values.

Define an integer to represent a boolean value:

int isTrue = 1;  // Represents true
int isFalse = 0; // Represents false

In C, any non-zero value is considered "true" while zero is considered "false". 

Use these boolean values in conditions:

int age = 25;
int isAdult = (age > 17);

printf("Is adult? %d\n", isAdult);
Output:
Is adult? 1

You can use comparison operators to produce boolean results. For example, > checks if the left value is greater than the right, and >= checks if the left value is greater than or equal to the right:

int age = 18;
int isAdult = (age >= 18); // true if age is 18 or older

printf("Is adult? %d\n", isAdult);
Output:
Is adult? 1

Starting with C99, you can include the <stdbool.h> header to use the boolean type:

#include <stdbool.h>

bool isTrue = true;   // Now using actual boolean type
bool isFalse = false; // Using predefined constants

Note: since the C23 standard, bool, true and false are keywords built into the language, so on a C23 compiler the header is no longer required. Most code and compilers you will meet still target C99 to C17, where <stdbool.h> is needed.

But you will learn more about the usage of booleans later throughout your journey

challenge icon

Challenge

Easy

Set the age variable to 16. Then, create a program that checks whether the person is old enough to drive (age 18 or older).
Store the comparison itself in a variable called canDrive, not a number you worked out: C turns the comparison into 1 (true) or 0 (false). The lines below your code print both the age and the result.

Try it yourself

    // Your code here: replace the zero with the age the task asks for
    int age = 0;

    // Your code here: replace the zero with the comparison that decides if the person is old enough to drive
    int canDrive = 0;
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online C compiler