Rule Definition
Explicitly declaring a bit-field unsigned prevents unexpected sign extension, overflows and implementation-defined behavior.
Note that if a bit-field has enumeration type, then the enumeration base needs to be declared of an explicitly unsigned type.
Remediation
Make sure bit fields are unsigned type or Enums with base defined as unsigned
Violation Code Sample
#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; // Non-compliant - signed integral type
bool c : 1; // Non-compliant - it is implementation-defined whether bool is
// signed or unsigned
char d : 2; // Non-compliant
wchar_t e : 2; // Non-compliant
E2 f2 : 2; // Non-compliant - E2 enum class underlying type is signed
// int
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
}
Fixed Code Sample
#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::uint8_t b : 2U; // Compliant
E1 f1 : 2; // Compliant
}
Reference
AUTOSAR C++ 2014, A9-6-1: Bit-fields shall be either unsigned integral or enumeration (with underlying type of unsigned integral type).
JSF December 2005 [7]: AV Rule 154 Bit-fields shall have explicitly unsigned
integral or enumeration types only.
HIC++ v4.0 [8]: 9.2.1 Declare bit-fields with an explicitly unsigned integral or
enumeration type.
https://cwe.mitre.org/data/definitions/190.html
Related Technologies
Technical Criterion
CWE-190 - Integer Overflow or Wraparound
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.