Where is struct with no named members useful?

Why and where does C standard allow this code compile? where is it useful?

struct foo {
  int : 12;
};

That would be in §6.7.2.1 Structure and union specifiers

12) A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field.126

The footnote explains why such things exist:

126 An unnamed bit-field structure member is useful for padding to conform to externally imposed layouts.

That being said, the same part of the standard (paragraph 8) also states:

If the struct-declaration-list does not contain any named members, either directly or via an anonymous structure or anonymous union, the behavior is undefined.

But some compilers (GCC and clang at least) allow this anyway, as an extension.

The use is a bit limited if that's the only bitfield in the struct, but not impossible to use as ouah illustrates.

The standard continues on with another "oddity":

As a special case, a bit-field structure member with a width of 0 indicates that no further bit-field is to be packed into the unit in which the previous bitfield, if any, was placed.


This program invokes undefined behavior.

C says:

(C99, 6.7.2.1p7) "[...] If the struct-declaration-list contains no named members, the behavior is undefined."

Now some compilers accept it as an extension. How can this be useful?

For example for Linux kernel famous BUILD_BUG_ON_ZERO macro:

#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))

To see what does this macro, you can look here.


Well, according to the language specification, if your program contains a struct type without named members, the behavior is undefined. (To the question of why it is not officially recognized as a constraint violation I have no immediate answer.) It is stated in 6.7.2.1/7

The struct-declaration-list is a sequence of declarations for the members of the structure or union. If the struct-declaration-list contains no named members, the behavior is undefined.

Other than that such declaration is not really "useful" since the only thing it produces is undefined behavior.

链接地址: http://www.djcxy.com/p/73558.html

上一篇: 如果两种类型不相同,则会导致C89中的编译错误

下一篇: struct没有命名的成员在哪里有用?