C++ 将 bool 转换为 int - 标准

标签 c++ casting boolean

我感兴趣的是,标准在将 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 转换为 1false 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/

相关文章:

在 C 中将 boolean 数组的元素更改为 false

c# - 在 Lambda 表达式中使用三元运算符

c++ - 访问 vector 容器的元素时发生运行时错误

php - PHP中简单数字的float到int改变值

C# 泛型和转换

casting - KDB+ 将符号转换为字符

ruby-on-rails - Rails 表单在提交时将 false 作为 boolean 值的默认值传递

c++ - Qt 不会链接任何东西

c++ - 根据文件读取条件初始化struct中char的大小

c++ - 为什么 SEM_NOGPFAULTERRORBOX 也抑制被零除?