Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to cast bool to float?

Tags:

c++

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?

like image 714
Zack Lee Avatar asked Dec 14 '22 11:12

Zack Lee


1 Answers

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.

like image 143
Nikita Smirnov Avatar answered Jan 12 '23 06:01

Nikita Smirnov