Reputation: 3044
I wonder if directly casting bool
to float
is safe to use.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
bool b1 = false;
bool b2 = true;
float f1 = static_cast<float>(b1);
float f2 = static_cast<float>(b2);
cout << "False in float : " << f1 << endl;
cout << "True in float : " << f2 << endl;
return 0;
}
Result:
False in float : 0
True in float : 1
Would the result be identical in all C++ compilers and platforms?
Upvotes: 9
Views: 8465
Reputation: 862
Yes, it should be safe across all compilers and platforms, this rule is guaranteed by the standard.
C++ draft standard, Section 4.9, Floating-integral conversions tells us:
If the source type is bool, the value false is converted to zero and the value true is converted to one.
Upvotes: 14
Reputation: 85757
Yes, this has been allowed and defined since the first C++ standard, ISO/IEC 14882:1998.
4.9 Floating-integral conversions [conv.fpint] says:
- An rvalue of an integer type or of an enumeration type can be converted to an rvalue of a floating point type. The result is exact if possible. Otherwise, it is an implementation-defined choice of either the next lower or higher representable value. [Note: loss of precision occurs if the integral value cannot be represented exactly as a value of the floating type. ] If the source type is
bool
, the valuefalse
is converted to zero and the valuetrue
is converted to one.
(Emphasis mine.)
Upvotes: 5