c++ - 将 bool 转换为位域中的位

标签 c++

我有一个位域:

struct MyBitfield {
  unsigned char field1: 1;
  unsigned char field2: 1;
};

这些位域参数是 1 位宽并表示 bool 值。我想知道用 bools 初始化它是否有效,如下所示

MyBitfield my_bitfield = {true, false};

我的问题是这种行为是否定义明确。 IIUC,false 始终计算为 0true 可以计算为任何非零整数。如果它碰巧求值为 LSB 为 0 的整数,它会被转换为位 0 并求值为 false 还是语言保证它总是被转换为 1 位?

最佳答案

简短回答:是的,语言保证它总是被转换为位 1。

长答案:

这里有一些很好的信息: Can I assume (bool)true == (int)1 for any C++ compiler?

If the source type is bool, the value false is converted to zero and the value true is converted to one.

http://en.cppreference.com/w/cpp/language/bool_literal :

#include <iostream>

int main()
{
  std::cout << std::boolalpha
            << true << '\n'
            << false << '\n'
            << std::noboolalpha
            << true << '\n'
            << false << '\n';
}

输出:

true
false
1
0

所以是的,语言保证它总是被转换为位 1。

关于c++ - 将 bool 转换为位域中的位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50924644/

相关文章:

c++ - 检测 IBeam 光标

c++ - 查找 vector 中最接近的值

c++ - CGAL:找到一个点所属的面/三角形?

c++ - ifstream 读取二进制数据发出 0x00 字节

c++ - 为什么程序结束后会失败

c++ - Doxygen:在几个嵌套组中对类进行分组

c++ Lock类骨架

c++ - 转换不同参数类型的二元运算函数

c++ - Visual C++ 项目引用的新手帮助

c++ - OpenCV CommandLineParser 未指定的参数