我有一个位域:
struct MyBitfield {
unsigned char field1: 1;
unsigned char field2: 1;
};
这些位域参数是 1 位宽并表示 bool 值。我想知道用 bools
初始化它是否有效,如下所示
MyBitfield my_bitfield = {true, false};
我的问题是这种行为是否定义明确。 IIUC,false
始终计算为 0
但 true
可以计算为任何非零整数。如果它碰巧求值为 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/