Question

What is the use of unnamed bit-fields in C?

Example :

typedef struct fun {
unsigned int                 :8;
unsigned int foo1            :1;
unsigned int foo2            :1;
unsigned int foo3            :1;
unsigned int foo4            :1;
unsigned int foo5            :1;
}dig;

What is the use of line :

   unsigned int                 :8;
Was it helpful?

Solution

It's called unnamed bit field. C11 standard states about it and possible usage:

6.7.2.1 Structure and union specifiers

A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field. 106) 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 bitfeld, if any, was placed.

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

OTHER TIPS

An unnaed bitfield like this can be used for a number of reasons. One reason as already mentioned is in order to pad out the other values in order to match an external layout where there are values that are unused. I have seen it used this way to map directly onto hardware.

They could also be left unnamed for future expansion

Although you can give a name to indicate it is unused it is possible for someone to set those bits using the field you have provided and by not naming it you make the user jump through hoops in order to set the bits. You also end up with unnamed1, unnamed2 etc scattering your bitfields

For example on a microprocessor I have used there are bits that are specifically for the debugger to use and by not naming them it makes them harder for a developer to set them unintentionally.

The problem was on a previous version they were named and a colleague used them. Update of the compiler and headers and no longer building code

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top