Main Content

MISRA C++:2023 Rule 12.2.1

Bit-fields should not be declared

Since R2024b

Description

Rule Definition

Bit-fields should not be declared.

Rationale

When you declare bit-fields in a structure or a union, the layout of those bit-fields is implementation-defined, For example:

  • A bit-field can be allocated starting from the most significant bit (high end) or starting from the least significant bit (low end).

  • A bit-field can span multiple storage units. For instance, if you declare a six-bit and a four-bit bit-field, some implementations store the bit-fields in separate bytes, while other implementations store two bits of the four-bit bit-field in the same byte as the six-bit bit-field and store the other two bits in the next storage unit.

In addition, if the bit-field contains padding bits, those extra bits do not contribute to the value representation of the bit-field.

Do not declare bit-fields if you do not need to make assumptions about their layout inside a structure or a union, for example, if you only access the members of the structure or a union by name.

The layout of bit-fields inside a structure or a union is important only when you use those bit-fields to manipulate the fields of a hardware register, because the hardware register fields have specific memory addresses.

Polyspace Implementation

This coding rule checker reports a violation if you declare bit-fields inside a structure or a union.

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

expand all

struct myStruct
{
    unsigned int val : 28; // Noncompliant
    unsigned int cnt : 12; // Noncompliant
};

In this example, Polyspace reports a violation on the bit-field declarations inside the structure myStruct. While the use of bit-fields can result in more compact storage, the layout of those bit-fields is implementation-defined, which makes the code less portable.

Check Information

Group: Classes
Category: Advisory

Version History

Introduced in R2024b