Menu
Coddy logo textTech

Booleans

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

In C, there is no built-in boolean data type like in other languages. Instead, 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 also use the >= (greater than or equal to) operator in conditions. For example, age >= 18 is true if age is 18 or more, and false otherwise:

int age = 18;
int isAdult = (age >= 18);

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

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 result (either 0 for false or 1 for true) in a variable called canDrive, and print both the age and the result.

Cheat sheet

C uses integers to represent boolean values:

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

Any non-zero value is considered "true" while zero is considered "false".

Use boolean values in conditions:

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

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

Common comparison operators used with booleans:

a > b   // greater than
a >= b  // greater than or equal to
a < b   // less than
a <= b  // less than or equal to
a == b  // equal to
a != b  // not equal to

For C99 and later, include <stdbool.h> for actual boolean type:

#include <stdbool.h>

bool isTrue = true;
bool isFalse = false;

Try it yourself

#include <stdio.h>

int main() {
    // Your code here:
    int age = ;

    // Your code here:
    int canDrive = ;

    printf("Age: %d\n", age);
    printf("Can drive? %d\n", canDrive);

    return 0;
}
quiz iconTest yourself

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

All lessons in Fundamentals