Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

Booleans

Booleans

Frequently in programming, you’ll encounter scenarios where you require a data type with only two possible values, such as:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

C offers a bool data type, referred to as booleans, for this purpose.

Booleans represent values that can be either true or false.

Boolean Variables

In C, the bool type is not inherently built-in like int or char.

Introduced in C99, to utilize the bool type, you need to include the following header file:

#include <stdbool.h

A boolean variable is declared using the bool keyword and is restricted to holding only the values true or false:

bool isProgrammingFun = true;
bool isFishTasty = false

Prior to attempting to print boolean variables, it’s important to note that boolean values are returned as integers:

  • 1 (or any non-zero number) signifies true.
  • 0 signifies false.

Hence, you should utilize the %d format specifier to print a boolean value:

Example

// Create boolean variables
bool isProgrammingFun = true;
bool isFishTasty = false;

// Return boolean values
printf(“%d”, isProgrammingFun);   // Returns 1 (true)
printf(“%d”, isFishTasty);        // Returns 0 (false) 

Yet, it’s more typical to obtain a boolean value through comparisons of values and variables.

Comparing Values and Variables

Value comparisons are valuable in programming as they enable us to find solutions and make decisions.

For instance, you can employ a comparison operator like the greater than ( > ) operator, to compare two values:

Example

printf(“%d”, 10 > 9);  // Returns 1 (true) because 10 is greater than 9 

 

From the instance above, it’s evident that the return value is a boolean value (1).

You can also perform comparisons between two variables:

Example

int x = 10;
int y = 9;
printf(“%d”, x > y); 

In the following example, we utilize the equal to (==) operator to compare distinct values:

Example

printf(“%d”, 10 == 10); // Returns 1 (true), because 10 is equal to 10
printf(“%d”, 10 == 15); // Returns 0 (false), because 10 is not equal to 15
printf(“%d”, 5 == 55);  // Returns 0 (false) because 5 is not equal to 55 

You’re not restricted to comparing only numbers. You can also compare boolean variables, or even specialized structures like arrays (which you’ll delve into further in a subsequent chapter):

Example

bool isHamburgerTasty = true;
bool isPizzaTasty = true;

// Find out if both hamburger and pizza is tasty
printf(“%d”, isHamburgerTasty == isPizzaTasty); 

 

Don’t forget to include the <stdbool.h> header file when utilizing bool variables.