Main Content

MISRA C++:2008 Rule 9-6-2

Bit-fields shall be either bool type or an explicitly unsigned or signed integral type

Description

Rule Definition

Bit-fields shall be either bool type or an explicitly unsigned or signed integral type.

Rationale

Using bit-fields require that their underlying bit representations are not implementation-defined. For types other than bool and signed or unsigned integral types, the underlying bit representation is not explicitly known. For instance, the underlying representation of an int bit-field can be either signed or unsigned based on implementation. Similarly, ISO/IEC 14882:2003 does not explicitly define the signedness of the underlying bit representation of wchar_t types.

Using types other than bool and signed or unsigned integral types as bit fields might result in code that behaves in an implementation-dependent manner and result in bugs that are difficult to diagnose. When using bit fields, use bool, signed integral types, or unsigned integral types.

Polyspace Implementation

Polyspace® reports a violation of this rule if the type of a bit field is:

  • An integral type that does not have an explicit sign specification

  • A wchar_t

Polyspace does not report a violation if the type of a bit field is:

  • A bool

  • An explicitly signed or explicitly unsigned integral type

  • An explicitly signed or unsigned char

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>
struct S
{
	signed int sInt_f : 2; // Compliant
	unsigned int uInt_f : 2; // Compliant
	char Ch_f : 2; // Noncompliant
	signed char sCh_f : 2; // Compliant
	unsigned char uCh_f : 2; // Compliant
	short Sh_f : 2; // Noncompliant
	signed short sSh_f : 2; // Compliant
	unsigned short uSh_f : 2; // Compliant
	int Int_f : 2; // Noncompliant
	bool Bool_f : 2; // Compliant
	wchar_t wch_f : 2; // Noncompliant
	int32_t sInt32_f : 2; // Noncompliant
	int8_t sInt8_f : 2; // Compliant
	long Long_f:2; //Noncompliant
	unsigned long uLong_f:2; //Compliant
};

In this example, Polyspace flags the integral type bit fields that are not explicitly signed or unsigned and the wchar_t type bit fields.

Check Information

Group: Classes
Category: Required

Version History

Introduced in R2013b