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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With