Bit fields can only have integral or enumeration type. If it is quite straightforward to check if an integral type can initialize a bit field, it
is however trickier with an enum type: the bit field has to be wide enough to store all the possible values of the enum.
In addition to this, the signedness of the enum should be consistent with the signedness of the bit field:
- an unsigned bit field can not be initialized with a signed enum type
- a signed bit field uses one bit to store the sign and this needs to be taken into account while comparing the size of the enum type with the
size of the bit field.
Noncompliant code example
enum Color {
BLUE = 16
} myColor;
enum Fruit {
ORANGE = 1,
APPLE = 2
} myFruit;
struct BitStructForColor {
unsigned int b : 2;
};
struct BitStructForFruit {
signed int b : 2;
};
void f(BitStructForColor &bColorStruct, BitStructForFruit &bFruitStruct) {
bColorStruct.b = myColor; // Noncompliant, myColor is too wide for the bit field
bFruitStruct.b = myFruit; // Noncompliant, one bit of the bit field is used to store the sign
}
Compliant solution
enum Color {
BLUE = 16
} myColor;
enum Fruit {
ORANGE = 1,
APPLE = 2
} myFruit;
struct BitStructForColor {
unsigned int b : 5;
};
struct BitStructForFruit {
signed int b : 3;
};
void f(BitStructForColor &bColorStruct, BitStructForFruit &bFruitStruct) {
bColorStruct.b = myColor;
bFruitStruct.b = myFruit;
}