Keith M Keith M - 2 months ago 13
C++ Question

Is the "Type of bit field too small for number of bits" error part of the C++ standard?

The following code generates MSVS Compiler Error C2034 in Visual Studio 2008:

struct TestStruct {
unsigned short var1 : 7;
unsigned short : 9;
bool var2 : 1;
bool : 15; // C2034
};


error C2034: 'TestStruct::': type of bit field too small for number of bits


However, the following code compiles successfully, which seems kind of dumb, because I'd think the compiler could have just done this automatically:

struct TestStruct {
unsigned short var1 : 7;
unsigned short : 9;
bool var2 : 1;
bool : 7;
bool : 8;
};


However, both code snippets compile on my Linux GCC compiler. Is one compiler more correct than the other, according to the C++ Standard? If so, which, and why?

Answer

Yes this is a bug in MSVS. That standard states in [class.bit]/1

[...]The value of the integral constant expression may be larger than the number of bits in the object representation (3.9) of the bit-field’s type; in such cases the extra bits are used as padding bits and do not participate in the value representation (3.9) of the bit-field.[...]

So the compiler should have added extra padding and only let you have a number of bits equal to CHAR_BIT * sizeof(bit_field_underlying_type).

Comments