Friday 11 January 2019

c - 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;
};

Answer



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.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...