Bit-fields can be used to allow flags or other integer values with small ranges to be packed together to save storage space.
It is implementation-defined whether the specifier
int designates the same type as
signed int or the same type as
unsigned int for bit-fields. According to the C Standard [ISO/IEC 9899:2011], C integer promotions also require that "if an
int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an
int; otherwise, it is converted to an
This issue is similar to the signedness of plain
char, discussed in INT07-C. Use only explicitly signed or unsigned char type for numeric values. A plain
int bit-field that is treated as unsigned will promote to
int as long as its field width is less than that of
int can hold all values of the original type. This behavior is the same as that of a plain
char treated as unsigned. However, a plain
int bit-field treated as unsigned will promote to
unsigned int if its field width is the same as that of
int. This difference makes a plain
int bit-field even trickier than a plain
Bit-field types other than
signed int, and
unsigned int are implementation-defined. They still obey the integer promotions quoted previously when the specified width is at least as narrow as
CHAR_BIT*sizeof(int), but wider bit-fields are not portable.
Noncompliant Code Example
This noncompliant code depends on implementation-defined behavior. It prints either
255, depending on whether a plain
int bit-field is signed or unsigned.
This compliant solution uses an
unsigned int bit-field and does not depend on implementation-defined behavior:
Making invalid assumptions about the type of a bit-field or its layout can result in unexpected program flow.
|Axivion Bauhaus Suite|
|LANG.TYPE.BFSIGN||Bit-field signedness not explicit|
|LDRA tool suite|
Bit fields shall only be defined to be of type unsigned int or signed int
|Polyspace Bug Finder|
Overflow when converting between integer types
Bit-fields shall only be declared with an appropriate type
|SonarQube C/C++ Plugin|
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
|SEI CERT C++ Coding Standard||VOID INT12-CPP. Do not make assumptions about the type of a plain int bit-field when used in an expression|
|ISO/IEC TR 24772:2013||Bit Representations [STR]|
|MISRA C:2012||Rule 10.1 (required)|
|[ISO/IEC 9899:2011]||Subclause 188.8.131.52, "Boolean, Characters, and Integers"|