简体   繁体   English

我可以或应该制作布尔位字段吗?

[英]Can or should I make bools bit fields?

Is this legal or recommended?这是合法的还是推荐的? I read that you should only use integer types as bitfields, but does this apply to boolean types?我读到你应该只使用整数类型作为位域,但这适用于布尔类型吗? Is this OK, or is this bad practice or undefined behavior somehow?这可以吗,或者这是不好的做法或未定义的行为?

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

Can ... I make bools bit fields?可以...我制作布尔位字段吗?

<\/blockquote>

Yes.是的。 It is one of 3 well defined choices.它是 3 个定义明确的选择之一。

A bit-field shall have a type that is a qualified or unqualified version of _Bool<\/code> , signed int<\/code> , unsigned int<\/code> , or some other implementation-defined type.位域的类型应为_Bool<\/code> 、 signed int<\/code> 、 unsigned int<\/code>或其他一些实现定义的类型的合格或非合格版本。 It is implementation-defined whether atomic types are permitted.是否允许原子类型是实现定义的。 C17dr § 6.7.2.1 5 C17dr § 6.7.2.1 5

<\/blockquote>


.... should I make bools bit fields? ....我应该制作布尔位字段吗?

<\/blockquote>

Yes, if it makes code more clear.是的,如果它使代码更清晰。

Note: this is one place to not use int x:1<\/code> as it is implementation defined if x<\/code> has values [0,1] or [-1,0].注意:这是一个不使用int x:1<\/code>的地方,因为如果x<\/code>具有值 [0,1] 或 [-1,0],它是实现定义的。 Use signed int x:1<\/code> or unsigned x:1<\/code> or _Bool x:1<\/code> for [-1,0], [0,1], [0,1] respectively.分别对 [-1,0]、[0,1]、[0,1] 使用有signed int x:1<\/code>或unsigned x:1<\/code>或_Bool x:1<\/code> 。

For x:1<\/code> , bool<\/code> does have a clearer functionally specification than signed int<\/code> when assigning an out-of-range value.对于x:1<\/code> ,在分配超出范围的值时, bool<\/code>的功能规范确实比有signed int<\/code>更清晰。 See comment<\/a> .评论<\/a>。 For unsigned<\/code> , just the LSbit is copied.对于unsigned<\/code> ,仅复制 LSbit。

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM