MISRA C++:2023 Rule 12.2.2
Description
Rule Definition
A bit-field shall have an appropriate type.
Rationale
Certain types are not appropriate for bit-fields because their signedness
is implementation-defined. For example, if you use the types
char
, wchar_t
, or an unscoped
enum
without specifying the underlying type, these
issues can occur:
The bit-field is too small to store its assigned value because its signedness limits the range of values it can assume.
Sign extension occurs when you assign a value to the bit-field, propagating the sign bit to higher-order bits and changing the interpretation of the value stored in the bit-field.
The types char16_t
and
char32_t
are also not appropriate for bit-fields
because they are intended to only represent Unicode characters in UTF-16
and UTF-32 encodings, respectively. Using types designed for Unicode
representation with bit-fields which are typically used for packing data
tightly can reduce code readability and make the code harder to
maintain.
Instead, use one of these types with bit-fields:
Signed or unsigned integer types.
A Boolean.
An enumerated type with an underlying type of signed or unsigned integer type. Bit-fields declared with these enumerated types must have bit widths large enough to accommodate all the values of the enumerated type.
Polyspace Implementation
The coding rule checker reports a violation when the underlying type of a bit-field is one of these:
A
char
orwchar_t
type.An unscoped enumeration with no specified underlying type.
An unscoped enumeration where width of the bit-field does not accommodate all the enumerator values.
Troubleshooting
If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Classes |
Category: Required |
Version History
Introduced in R2024b