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.1 - Bit-fields should not be declared
[class.bit] Implementation 1
Category: Advisory
Analysis: Decidable,Single Translation Unit
Rationale
There are a number of aspects of bit-fields that a developer needs to consider, including:
- It is implementation-defined whether the bit-fields are allocated from the high or low end of a storage unit (usually a byte);
- It is implementation-defined whether or not a bit-field can overlap a storage unit boundary (e.g. if a 6-bit bit-field and a 4-bit
bit-field are declared in that order, then the 4-bit bit-field may either start a new byte or it may use 2 bits in one byte and 2 bits in the next);
- If the bit-field’s width is greater than the number of bits in the object representation of the bit-field’s type, then the extra bits are
padding bits and do not participate in the value representation of the bit-field.
These issues are generally benign (e.g. when packing together short-length data to save storage space), but they may lead to errors if the absolute
position of the bit-fields is important (e.g. when accessing hardware registers).
Provided the elements of the structure are only accessed by name, the developer need make no assumptions about the way that the bit-fields are
stored within the structure.
Example
struct message
{
unsigned char low : 4; // Non-compliant
unsigned char high : 4; // Non-compliant
};
Copyright The MISRA Consortium Limited © 2023