是否保证
将 true 赋值给 float 变量导致 1.0f
将 false 赋给 float 变量导致 0.0f
测试上述变量的真实性会按预期返回(分别为 true 和 false?)
最佳答案
是的。对于前两个,4.9/2(“浮点积分转换”):
If the source type is bool, the value false is converted to zero and the value true is converted to one.
对于最后一个,4.12/1(“boolean 转换”):
A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.
另外,我想您需要知道它保证为零,而一个可以表示为 float
的值。上面暗示了这一点(否则转换不能像描述的那样运行),但我不确定它是否以及在哪里明确说明哪些整数值需要在 float
中精确表示。
引文来自 N3337,几乎完全是 C++11。标签已更改为“C++”而不是“C++11”——C++03 中的规则相同,但措辞和段落编号可能不同。
关于c++ - 为 float 分配真值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11447709/