bool, true, & false
Before bool became part of
Standard C++, everyone tended to use different techniques in order to produce
Boolean-like behavior.
These
produced portability problems and could introduce subtle
errors.
The Standard C++ bool type can
have two states expressed by the built-in constants true (which converts
to an integral one) and false (which converts to an integral zero). All
three names are keywords. In addition, some language elements have been
adapted:
|
|
|
Take bool arguments and produce
bool results.
|
|
|
|
Conditional expressions convert to
bool values.
|
|
First operand converts to bool
value.
|
Because there’s a lot of existing
code that uses an int to represent a flag, the compiler will implicitly
convert from an int to a bool (nonzero values will produce true
while zero values produce false). Ideally, the compiler will
give you a warning as a suggestion to correct the situation.
An idiom that falls under “poor
programming style” is the use of ++ to set a flag to true. This is
still allowed, but deprecated, which means that at
some time in the future it will be made illegal. The problem is that
you’re making an implicit type conversion from bool to int,
incrementing the value (perhaps beyond the range of the normal bool
values of zero and one), and then implicitly converting it back
again.
Pointers (which will be introduced later
in this chapter) will also be automatically converted to bool when
necessary.