Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is struct with no named members useful?

Tags:

c

struct

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

struct foo {
  int : 12;
};
like image 630
The Mask Avatar asked Oct 04 '13 21:10

The Mask


1 Answers

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.

like image 95
Mat Avatar answered Oct 04 '22 06:10

Mat