简体   繁体   English

将bool转换为浮动是否安全?

[英]Is it safe to cast bool to float?

I wonder if directly casting bool to float is safe to use. 我想知道是否可以直接将boolfloat使用。

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? 在所有C ++编译器和平台中,结果是否相同?

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: C ++草案标准 ,第4.9节,浮动积分转换告诉我们:

If the source type is bool, the value false is converted to zero and the value true is converted to one. 如果源类型为bool,则将值false转换为零,将值true转换为一。

Yes, this has been allowed and defined since the first C++ standard, ISO/IEC 14882:1998. 是的,自第一个C ++标准ISO / IEC 14882:1998以来,这已被允许和定义。

4.9 Floating-integral conversions [conv.fpint] says: 4.9浮动积分转换[conv.fpint]说:

  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. 如果源类型为bool ,则将值false转换为零,将值true转换为一。

(Emphasis mine.) (强调我的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM