我感兴趣的是,标准在将 bool
类型转换为 integer
类型后是否会说明任何可能的值。
例如下面的代码:
#include <iostream>
using namespace std;
int main() {
bool someValue=false;
*((int*)(&someValue)) = 50;
cout << someValue << endl;
return 0;
}
即使它被强制存储值 50 也打印 1。标准是否指定任何相关内容?或者编译器是否为 bool 类型生成一些方法:
operator int(){
return myValue !=0 ? 1 : 0;
}
还有为什么像下面这样类型转换:
reinterpret_cast<int>(someValue) = 50;
错误禁止
error: invalid cast from type 'bool' to type 'int'
(对于以上所有内容,我使用 GCC 5.1 编译器。)
最佳答案
您使用它的方式展示了 UB,因为您在 bool 变量的边界之外编写并且您违反了严格的别名规则。
但是,如果您有一个 bool 并希望将其用作 int(这通常发生在您希望根据某些条件对数组进行索引时),标准要求 true
bool 转换为 1
和 false
bool 转换为 0
,无论如何(UB 显然排除)。
例如,只要 should_add == true
就保证输出 52
。
int main(){
int arr[] = {0, 10};
bool should_add = 123;
int result = 42 + arr[should_add];
std::cout << result << '\n';
}
关于C++ 将 bool 转换为 int - 标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38582749/