CBooleans
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 abool data type, which is known asbooleans.
Booleans represent one of two values:true orfalse.
Boolean Variables
In C, thebool type is not a built-in data type, likeint orchar.
It was introduced in C99, and you mustimport the following header file to use it:
A boolean variable is declared with thebool keyword and can take the valuestrue orfalse:
bool isFishTasty = false;
Before trying to print the boolean variables, you should know that boolean values are returned asintegers:
1(or any other number that is not 0) representstrue0representsfalse
Therefore, you must use the%d format specifier to print a boolean value:
Example
bool isProgrammingFun = true;
bool isFishTasty = false;
// Return boolean values
printf("%d", isProgrammingFun); // Returns 1 (true)
printf("%d", isFishTasty); // Returns 0 (false)
However, it is more common to return a boolean value bycomparing values and variables.
Comparing Values and Variables
Comparing values are useful in programming, because it helps us to find answers and make decisions.
For example, you can use acomparison operator, such as thegreater than (>) operator, to compare two values:
From the example above, you can see that the return value is a boolean value (1).
You can also compare two variables:
In the example below, we use theequal to (==) operator to compare different values:
Example
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 are not limited to only compare numbers. You can also compare boolean variables, or even special structures, likearrays (which you will learn more about in a later chapter):
Example
bool isPizzaTasty = true;
// Find out if both hamburger and pizza is tasty
printf("%d", isHamburgerTasty == isPizzaTasty);
Remember to include the<stdbool.h> header file when working withbool variables.

