Rule A9-6-1 (required, design, partially automated)

Data types used for interfacing with hardware or conforming to communication protocols shall be trivial, standard-layout and only contain members of types with defined sizes.

Rationale

When the layout of data types is important, only those types that have a defined size shall be used (see A3-9-1, this excludes bool, wchar_t, pointers, and pointers to members). Enumeration types may be used if they have been explicitly declared with an underlying type that has a defined size. Note: As the use of bit-fields is only allowed for interfacing with hardware or conforming to communication protocols, this restriction on types also applies to bitfields, see A9-6-2. Note: The signed exact-width integer types like std::int16_t are guaranteed to have a two’s complement representation.

Example

// $Id: A9-6-1.cpp 319312 2018-05-15 08:29:17Z christof.meerwald $
#include <cstdint>

enum class E1 : std::uint8_t
{
E11,
E12,
E13
};
enum class E2 : std::int16_t
{
E21,
E22,
E23
};
enum class E3
{
E31,
E32,
E33
};
enum E4
{
E41,
E42,
E43
};

class C
{

public:
std::int32_t a : 2;
std::uint8_t b : 2U;

// Compliant
// Compliant

bool c : 1;

// Non-compliant - the size of bool is implementation defined

char d : 2;
// Non-compliant
wchar_t e : 2; // Non-compliant - the size of wchar_t is implementation defined

E1 f1
: 2;
// Compliant
E2 f2
: 2;
// Compliant
E3 f3 : 2;// Non-compliant - E3 enum class does not explicitly define
// underlying type
E4 f4 : 2; // Non-compliant - E4 enum does not explicitly define underlying
// type

};

struct D
{
std::int8_t a;

// Compliant

bool b;

// Non-compliant - the size of bool is
// implementation defined

std::uint16_t c1
std::uint16_t c2

: 8;
: 8;

// Compliant
// Compliant

};

void Fn() noexcept
{
C c;
c.f1 = E1::E11;
}

See also

MISRA C++ 2008 [7]: A9-6-2: Bit-fields shall be either bool type or an explicitly unsigned or signed integral type JSF December 2005 [8]: AV Rule 154: Bit-fields shall have explicitly unsigned integral or enumeration types only HIC++ v4.0 [9]: 9.2.1: Declare bit-fields with an explicitly unsigned integral or enumeration type Rule A9-6-2 (required, design, non-automated) Bit-fields shall be used only when interfacing to hardware or conforming to communication protocols.

Rationale

Usage of bit-fields increases code complexity and certain aspects of bit-field manipulation can be error prone and implementation-defined. Hence a bit-field usage is reserved only when interfacing to hardware or conformance to communication protocols Note: A9-6-1 restricts the types allowed to be used in these contexts.


## See also
JSF December 2005 [8]: AV Rule 155: Bit-fields will not be used to pack data
into a word for the sole purpose of saving space.