Summary: in this tutorial, you’ll learn about the C Boolean type and how to use the Boolean values effectively in your program.
Introduction to the C Boolean type
In programming, the Boolean type has two possible values that represents the truth values: true
and false
.
C doesn’t natively support boolean type. In C, zero means false
. And other values are true
. For example, all the numbers which are not zero are true
.
To make it more convenient to work with the Boolean values, the community employed a number of techniques. And one of them is to define a Boolean type using the enum
type;
typedef enum {false, true} bool;
Code language: C++ (cpp)
ANSI C99 added the Boolean type in the stdbool.h
header file. To use the standard Boolean type, you need to include the stdbool.h
file in your program.
The standard Boolean type uses the bool
keyword as the type. It has two values true
and false
. Internally, true
evaluates to 1 and false
evaluates to 0.
To declare a Boolean variable, you use the bool
keyword as follows:
bool is_running = true;
bool is_shared = false;
Code language: C++ (cpp)
In this example, we declared two variables is_running
and is_shared
and assigned true
and false
to each.
When you print out a Boolean value using the printf()
function, you still need to use the %d
specificier. For example:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool is_running = true;
bool is_shared = false;
printf("is_running: %d\n", is_running); // 1
printf("is_shared: %d\n", is_shared); // 0
return 0;
}
Code language: C++ (cpp)
As clearly shown in the output, the boolean values evaluate to 1 and 0 instead of true and false.
If you want to output true
and false
for a boolean value, you can use an if...else
statement or a ternary operator. For example:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool success = false;
puts(success ? "true" : "false"); // false
success = true;
puts(success ? "true" : "false"); // true
return 0;
}
Code language: C++ (cpp)
The ?: is called the ternary operator in C. It has the following syntax:
Code language: C++ (cpp)expression ? value_if_true : value_if_false;
The ternary operator (?:
) evalutates the expression
. If the result is true
, it returns the value that follows the ?
. Otherwise, it returns the value that follows the :
.
Note that you’ll learn more about the ternary operator in the ternary operator tutorial.
In this example, the program first outputs false because the success is false. After that, the success is true, therefore, the program displays true.
Summary
- The Boolean type has two possible truth values:
true
andfalse
. - C doesn’t support the Boolean type natively. Instead, it uses 0 as
false
and other values astrue
. - Include the
stdbool.h
file in the program and use thebool
keyword for declaring the boolean variables.