我可以或应该制作 bools 位域吗?

Can or should I make bools bit fields?

这是合法的还是推荐的?我读到你应该只使用整数类型作为位域,但这是否适用于布尔类型?这样可以吗,还是这种不好的做法或未定义的行为?

struct MyStruct {
    // ...
    bool SomeBooleanProperty:1;
    // ...
};

Can ... I make bools bit fields?

是的。它是 3 个定义明确的选择之一。

A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted. C17dr § 6.7.2.1 5


.... should I make bools bit fields?

是的,如果它使代码更清晰。

注意:这是一个不使用 int x:1 的地方,因为如果 x 的值为 [0,1] 或 [-1,0],则它是实现定义的。分别对 [-1,0]、[0,1]、[0,1] 使用 signed int x:1unsigned x:1_Bool x:1

对于 x:1bool 在分配超出范围的值时确实比 signed int 具有更清晰的功能规范。参见 。对于 unsigned,只复制 LSbit。