Download Our Mobile App
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 values that are either true or false.
In C, the bool type is not a built-in data type, like int or char.
It was introduced in C99, and you must import the following header file to use it:
A boolean variable is declared with the bool keyword and can only take the values true or 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) represents true
0 represents false
Therefore, you must use the %d format specifier to print a boolean value:
However, it is more common to return a boolean value by 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 a comparison operator, such as the greater 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 the equal to (==) operator to compare different values:
You are not limited to only compare numbers. You can also compare boolean variables, or even special structures, like arrays
Remember to include the <stdbool.h> header file when working with bool variables.