Can I assume (bool)true == (int)1 for any C++ compiler?
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.
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.