This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 12.2.2 - A bit-field shall have an appropriate type
[class.bit] / 3, 4; Implementation 1
[basic.fundamental] / 5; Implementation 1
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
The following types are appropriate for a bit-field:
- Signed and unsigned integer types;
- An
enum with a fixed underlying type of signed or unsigned integer type, provided that all of its enumeration
values are representable within the width of the bit-field;
-
bool.
Rationale
The char and wchar_t types shall not be used for bit-fields as it is implementation-defined if they are signed
or unsigned. The char16_t and char32_t types are not permitted as they are only intended to be used to store character code
points.
Similarly, when using an unscoped enum without specifying the underlying type, it is implementation-defined if the underlying
representation is signed or unsigned. Therefore, the exact number of bits required to represent all values in the enumeration is also
implementation-defined.
Example
struct S
{
signed int a : 2; // Compliant
int : 2; // Compliant
int32_t b : 2; // Compliant
char c : 2; // Non-compliant
signed char d : 2; // Compliant - signed integer type
wchar_t e : 2; // Non-compliant - not a signed or unsigned integer type
char32_t f : 2; // Non-compliant - not a signed or unsigned integer type
bool g : 1; // Compliant
};
enum Direction { Top, Left, Bottom, Right };
enum Colour : char { Red, Pink, Blue };
enum Line : unsigned char { Plain, Dash, Dot};
struct S
{
Direction dir : 4; // Non-compliant - unscoped and no underlying type
Colour lineColour : 2; // Non-compliant - underlying type is plain char
Line lineStyle1 : 1; // Non-compliant - cannot represent Dot
Line lineStyle2 : 2; // Compliant
};
Copyright The MISRA Consortium Limited © 2023