S
Stephen Sprunk
No, the logical solution is *not to compare Boolean values to true*.
"if (2)" isn't likely to occur in real code, but if you have a
variable like "ok" whose value is logically Boolean (whether it's
declared as bool, _Bool, int, or something else), then the way to
test it is simply:
if (ok) ...
Writing this:
if (ok == true) ...
make no more sense than this:
if ((ok == true) == true) ...
That much is fair. I prefer "if (ptr)" over "if (ptr!=NULL)" as well.
I'll note, though, that "if (ok!=false)" works just fine, even for
uncommon values of truth.
There are issues when you want to compare two non-constant Boolean
values to each other. For example, you might have two Boolean functions
that are supposed to compute the same result, and you want to verify
that they behave consistently. In that case, what you really want to do
is:
if (func1() == func2()) ...
which can fail if they return int, and one of them returns 1 while the
other returns 2 (both true values). In that case, you need some
additional logic to avoid that kind of problem -- such as:
if ((bool)func1() == (bool)func2()) ...
That's just working around a bug: the functions return int instead of
returning bool.
(assuming your compiler gets this right), or:
if (!!func1() == !!func2()) ...
or "if (!func1() == !func2())". I've done that before.
But for most uses of _Bool, or bool, or even int used to hold logically
Boolean values, it's easy enough to write your code in a way that (a) is
straightforward, and (b) works correctly whether there are multiple true
values or not.
I agree, but that is a skill that we had to learn _because_ C didn't
have a real boolean type. Perhaps it was so long ago for you that you
don't remember it, but I do. And it's an obvious source of bugs,
particularly when a function only rarely returns a value other than 1
for truth.
I prefer that the language match the meaning as closely as possible, so
that my code is self-documenting, which often happens to enable more
aggressive compiler optimization as a side effect.
Do you eschew unsigned types because signed ones are good enough and
_you_ know that a particular variable will never be negative, even if
the compiler doesn't? No, because you're used to them and know that, in
certain cases, unsigned types work better. I assert the same would be
true if you were used to having a true boolean type.
S