Frequently in programming, you’ll encounter scenarios where you require a data type with only two possible values, such as:
C offers a bool data type, referred to as booleans, for this purpose.
Booleans represent values that can be either true or false.
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:
0
signifies false.Hence, you should utilize the %d format specifier to print a boolean value:
// Create boolean variables bool isProgrammingFun = true; bool isFishTasty = false; // Return boolean values |
Yet, it’s more typical to obtain a boolean value through comparisons of 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:
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:
int x = 10; int y = 9; printf(“%d”, x > y); |
In the following example, we utilize the equal to (==) operator to compare distinct values:
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):
bool isHamburgerTasty = true; bool isPizzaTasty = true; // Find out if both hamburger and pizza is tasty |
Don’t forget to include the <stdbool.h> header file when utilizing bool variables. |