Understanding underlying type of C/C++ bit fields

471 views Asked by At

When reading Microsoft Docs on C++ Bit Fields 1st code paragraph, the sentence ‘Note that nYear is 8 bits long and would overflow the word boundary of the declared type’ is a bit difficult to understand.

// bit_fields1.cpp
// compile with: /LD
struct Date {
   unsigned short nWeekDay  : 3;    // 0..7   (3 bits)
   unsigned short nMonthDay : 6;    // 0..31  (6 bits)
   unsigned short nMonth    : 5;    // 0..12  (5 bits)
   unsigned short nYear     : 8;    // 0..100 (8 bits)
};

My understanding of it is that an ‘underlying type’ is some sort of a ‘container type’ where the number of ‘declared bit fields’ must be less than or equal to the ‘bits of container type’. Also ‘continuous bit field declarations’ with the same ‘underlying type’ will always combine if possible except a (underlying type) : 0; is encountered.

// bit_fields2.cpp
// compile with: /LD
struct Date {
   unsigned nWeekDay  : 3;    // 0..7   (3 bits)
   unsigned nMonthDay : 6;    // 0..31  (6 bits)
   unsigned           : 0;    // Force alignment to next boundary.
   unsigned nMonth    : 5;    // 0..12  (5 bits)
   unsigned nYear     : 8;    // 0..100 (8 bits)
};

In this case, the ‘Force alignment to next boundary indicator’ is a separator between 2 container types.

In the 1st case, ‘overflow the word boundary of the declared type’ only means there is not enough bits in the 1st ‘container type’ to hold 8 bits, if the nYear line is changed to unsigned short nYear : 2;, then the size of Date will be exactly 2 (tested with VS2019).

Is this kind of understanding a correct approach? Or are there any glitches in terminology? Comments are appreciated.

0

There are 0 answers