Boolean Literals To initialize Boolean types, you use two Boolean literals,
true
and
false
.
Format Specifiers There is no format specifier for
bool
, but you can use the
int
format speci-
fier
%d
within
printf
to yield a
1
for true and a
0
for false. The reason is that
printf
promotes any integral value smaller than an
int
to an
int
. Listing 2-5
illustrates how to declare a Boolean variable and inspect its value.
Types
39 #include int main() {
bool b1 = true;
u
// b1 is true
bool b2 = false;
v
// b2 is false
printf("%d %d\n", b1, b2);
w
}
1 0
w
Listing 2-5: Printing bool variables with a printf statement You initialize
b1
to
true
u
and
b2
to
false
v
. By printing
b1
and
b2
as
integers (using
%d
format specifiers), you get 1 for
b1
and 0 for
b2
w
.
Comparison Operators Operators are functions that perform computations on operands. Operands
are simply objects. (“Logical Operators” on page 182 covers a full menu of
operators.) In order to have meaningful examples using
bool
types, you’ll
take a quick look at comparison operators in this section and logical opera-
tors in the next.
You can use several operators to build Boolean expressions. Recall that
comparison operators take two arguments and return a
bool
. The available
operators are equality (
==
), inequality (
!=
), greater than (
>
), less than (
<
),
greater than or equal to (
>=
), and less than or equal to (
<=
).
Listing 2-6 shows how you can use these operators to produce Booleans.
#include int main() {
printf(" 7