7

When you define a bitfield, you can leave some bits blank in the middle and assign members to specific bits. Why are some bits emptying in the middle?

struct product {
    unsigned int code : 6;    // product code : 6 bit
    unsigned int : 10;    // not use 10 bit
    unsigned int color : 5;    // product color : 5 bit
    unsigned int : 5;    // not use 5 bit
    unsigned int size : 6;    // product size : 3 bit
};

I don't know why I don't use the bit in the middle

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Possible duplicate of [Purpose of empty bit fields in a structure?](https://stackoverflow.com/questions/35075688/purpose-of-empty-bit-fields-in-a-structure) – Achal Jun 17 '19 at 12:14

3 Answers3

6

The bitfields are structured to avoid crossing word and byte boundaries. The first two, 6 and 10 bits, add up to 16 bits, while the other three, 5 and 5 and 6, also add up to 16 bits. It could be very inefficient to have a bit field be part of 2 separate 16 bit words.

Roel Balink
  • 417
  • 1
  • 4
  • 19
Deepstop
  • 3,627
  • 2
  • 8
  • 21
3

This is a very handy feature. Most of the hardware registers have so gaps of unused/reserved bits for example:

enter image description here

Unnamed bitfields save us from having fields with the reserved1, reserved2 , ... names

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Note that this depends on implementation defined behavior regarding the ordering of bit fields in a struct. – dbush Jun 17 '19 at 13:27
  • Hardware specific stuff is almost always designed for the specific implementation and it is not the issue here. – 0___________ Jun 17 '19 at 13:31
2

It is an unnamed bit-field, basically used-defined bit padding. From C17 6.7.2.1:

A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field. 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.

So I would guess it is used to get a certain memory layout, perhaps to correspond with a certain pre-defined hardware register or communication protocol.

But also please note that it isn't well-defined which bit that's the MSB, and that the compiler if free to add padding of its own, so this bit-field isn't portable between compilers or systems. It is best to avoid bit-fields entirely, for any purpose.

Lundin
  • 195,001
  • 40
  • 254
  • 396