Can I assume (bool)true == (int)1
for any C++ compiler ?
views:
507answers:
7No, TRUE can be arbitrary among compilers. Some will use 1, some -1 (all bits set, signed var), other compilers may use a different value. Even if the value is standardized, not all compilers may follow the standard.
FALSE, however, is when all bits are clear, which only happens for the numeric value 0.
Yes. The casts are redundant. In your expression:
true == 1
Integral promotion applies and the bool value will be promoted to an int
and this promotion must yield 1.
Reference: 4.7 [conv.integral] / 4: If the source type is bool
... true
is converted to one.
You should never check for true
, and you should never have to. The value may be completely arbitrary, the only guarantee you have is that false == 0
, and that true != false
.
I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.
Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."
Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...
Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as int
s that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h>
only require zero or non-zero, not necessarily zero or one.
If you cast that to bool
, zero will convert to false, and non-zero to true (as you'd expect).
According to the standard, you should be safe with that assumption. The C++ bool
type has two values - true
and false
with corresponding values 1 and 0.
The thing to watch about for is mixing bool
expressions and variables with BOOL
expression and variables. The latter is defined as FALSE = 0
and TRUE != FALSE
, which quite often in practice means that any value different from 0 is considered TRUE
.
A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL
to bool
if the BOOL
value is different than 0 or 1.