Zack Lee
Zack Lee

Reputation: 3044

Is it safe to cast bool to float?

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

Answers (2)

Nikita Smirnov
Nikita Smirnov

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

melpomene
melpomene

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:

  1. 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 value false is converted to zero and the value true is converted to one.

(Emphasis mine.)

Upvotes: 5

Related Questions