Main Content

MISRA C++:2023 Rule 12.2.3

A named bit-field with signed integer type shall not have a length of one bit

Since R2024b

Description

Rule Definition

A named bit-field with signed integer type shall not have a length of one bit.

Rationale

A bit-field with a signed integer type and a bit-width of one bit can behave in an unexpected way, can have a value that the developer does not expect, and is likely to be an error. For example, signed integer types of a fixed width such as std::int16_t have a two's complement representation. This representation uses the most significant bit to represent the sign of the value, which leaves not bit to represent the magnitude of the value. In this case, the bit-field can represent only 0 or -1.

The rule does not apply to anonymous signed bit-fields, regardless of their length, because those bit-fields are inaccessible.

Polyspace Implementation

The coding rule checker reports a violation when you declare a named bit-field with a signed integer type and a length of one bit.

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

#include <cstdint>

typedef struct
{
   std::uint16_t IOFlag :1;    //Compliant - unsigned type
   std::int16_t InterruptFlag :1; //Noncompliant
   std::int16_t Register1Flag :2; //Compliant - Length more than one bit
   std::int16_t : 1; //Compliant - Unnamed
   std::int16_t : 0; //Compliant - Unnamed
   std::uint16_t SetupFlag :1; //Compliant - unsigned type
} InterruptConfigbits_t;

In this example, only the second bit-field declaration is noncompliant. A named variable is declared with a signed integer type and a length of one bit.

Check Information

Group: Classes
Category: Required

Version History

Introduced in R2024b