Why is this an issue?
Some types are not very well suited for use in a bit-field, because their behavior is implementation-defined. When defining a bit-field, you should
stick to the following safe and portable types:
- In C:
signed short
, unsigned short
, signed char
, unsigned char
, signed int
,
unsigned int
or _Bool
- In C++ before C++14: all enumerated types, as well as
signed short
, unsigned short
, signed char
,
unsigned char
, signed int
, unsigned int
, signed long
, unsigned long
, signed
long long
, unsigned long long
or bool
- In C++ starting at C++14: all enumerated and integral types
Noncompliant code example
// Assuming we are in C
int b:3; // Noncompliant - may have the range of values 0..7 or -4..3
Compliant solution
unsigned int b:3;
Resources
- MISRA C:2004, 6.4 - Bit fields shall only be defined to be of type unsigned int or signed int.
- MISRA C++:2008, 9-6-2 - Bit-fields shall be either bool type or an explicitly unsigned or signed integral type.
- MISRA C:2012, 6.1 - Bit-fields shall only be declared with an appropriate type
- CERT, INT12-C. - Do not make assumptions about the type of a plain int bit-field
when used in an expression