问题
I was running code quality check on my C project, which involves structures with bit fields. I came across a situation which, as per MISRA C 2004 standards, rule # 6.4 - is a violation, that reads as follows: "6.4 Bit fields shall only be defined to be of type unsigned int or signed int." Literature available on Microsoft Developer Network here asserts this. Can anyone explain as to why the datatypes of the bitfield member needs to be signed or unsigned int? Why am I not allowed to do the following, even though, the following code would compile with no warnings:
typedef struct
{
char a: 4;
char b: 4;
char flag: 1;
}MY_STRUCT
回答1:
The primary reason is that if you don't explicitly state signed
or unsigned
, you don't know whether the type will be treated as signed
or unsigned
except by reading the implementation's definition of what it does. That means that portable code cannot be written without using the types with an explicit signedness keyword. (Note, too, that using char
for a bit-field type designator is using an implementation-defined type.)
ISO/IEC 9899:2011 — §6.7.2.1 Structure and union specifiers
A bit-field shall have a type that is a qualified or unqualified version of
_Bool
,signed int
,unsigned int
, or some other implementation-defined type.…
A bit-field is interpreted as having a signed or unsigned integer type consisting of the specified number of bits.125)
125)As specified in 6.7.2 above, if the actual type specifier used is
int
or a typedef-name defined asint
, then it is implementation-defined whether the bit-field is signed or unsigned.
That refers to:
§6.7.2 Type specifiers
¶4 The expression that specifies the width of a bit-field shall be an integer constant expression with a non-negative value that does not exceed the width of an object of the type that would be specified were the colon and expression omitted.
¶5 … except that for bitfields, it is implementation-defined whether the specifier
int
designates the same type assigned int
or the same type asunsigned int
.
回答2:
I didn't write the standard, so I can only speculate.
That said, my speculation would be that is is confusing to use integer types of different widths when the width actually doesn't make a difference (since you specify the number of bits anyway). For example:
char a : 4
short a : 4
int a : 4
all declare the same thing, so there is no reason to allow for confusion by having different ways of writing it.
来源:https://stackoverflow.com/questions/23987376/why-do-bit-fields-in-c-need-to-be-defined-of-type-unsigned-int-or-signed-int