C Booleans
Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:
- YES / NO
- ON / OFF
- TRUE / FALSE
For this, C has a bool data type, which is known as booleans.
Booleans represent one of two values: true or false.
Boolean Variables
In C, the bool type is not a built-in data type, like int or char.
It was introduced in C99, and you must include the following header file to use it:
#include <stdbool.h>
A boolean variable is declared with the bool keyword and can take the
values true or false:
bool isProgrammingFun = true;
bool isFishTasty = false;
Before trying to print the boolean variables, you should know that boolean values are returned as integers:
1(or any other number that is not 0) representstrue0representsfalse
Therefore, you can use the %d format specifier to print a boolean value:
Example
// Create boolean variables
bool isProgrammingFun = true;
bool isFishTasty = false;
// Print boolean values
printf("%d", isProgrammingFun); // Prints 1 (true)
printf("%d", isFishTasty); // Prints 0 (false)
Try it Yourself »
However, it is more common to get boolean values by comparing values and variables.
Comparing Values and Variables
Comparing values are useful in programming, because they help us to find answers and make decisions.
For example, you can use a comparison operator,
such as the greater than (>)
operator, to compare two values:
In C, comparisons return 1 (true) or 0 (false).
You can also compare two variables:
In the example below, we use the equal to (==)
operator to compare different values:
Example
printf("%d", 10 == 10); // Prints 1 (true), because 10 is equal to 10
printf("%d", 10 == 15); // Prints 0 (false), because 10 is not equal to 15
printf("%d", 5 == 55); // Prints 0 (false), because 5 is not equal to 55
Try it Yourself »
You are not limited to comparing numbers. You can also compare boolean variables:
Example
bool isHamburgerTasty = true;
bool isPizzaTasty = true;
// Find out if both hamburger and pizza are tasty
printf("%d", isHamburgerTasty == isPizzaTasty);
Try it Yourself »
Remember to include the <stdbool.h> header file when working with bool variables.
Storing Comparison Results
You can also store the result of a comparison in a bool
variable:
Example
int x = 10;
int y = 9;
bool isGreater = x > y;
printf("%d", isGreater); // Prints 1 (true)
Try it Yourself »
Note: It is up to you whether you store the result of a comparison in a boolean variable
or use the comparison directly.
Storing the result can make your code easier to read, especially if you want to reuse it.