其他分享
首页 > 其他分享> > c – 是否允许位字段的聚合初始化?

c – 是否允许位字段的聚合初始化?

作者:互联网

我有一个包含位字段的结构:

struct Foo {
    unsigned a : 16, b : 16;
};

我想知道我是否可以在它的位字段上使用聚合初始化.例如:

struct Foo bar = {13, 42};

我注意到这个does work in gcc 5.1和Visual Studio 2015.我只是想要证明这是C和C的标准批准初始化.

解决方法:

从C 14 [dcl.init.aggr]我们有

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

所以Foo是聚合初始化的聚合资格.然后我们有

When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order.[…]

Static data members and anonymous bit-fields are not considered members of the class for purposes of aggregate initialization.

所以在你的情况下,它们将被初始化,因为它们不是匿名的,它们将按照它们在结构中出现的顺序进行初始化.

从C11 6.2.5(21)我们得到

Arithmetic types and pointer types are collectively called scalar types. Array and structure types are collectively called aggregate types.46)

所以在C中我们仍在处理聚合.然后在6.7.9(9)我们有

Except where explicitly stated otherwise, for the purposes of this subclause unnamed members of objects of structure and union type do not participate in initialization. Unnamed members of structure objects have indeterminate value even after initialization.

和6.7.9(17)

Each brace-enclosed initializer list has an associated current object. When no
designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.148) In contrast, a designation causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator.149)

因此,我们具有与C中相同的行为,其中匿名位字段未初始化但由于它们被命名,因此它们将按它们在结构中出现的顺序进行初始化.

标签:c-3,bit-fields,c,initialization,aggregate-initialization
来源: https://codeday.me/bug/20190724/1525980.html