我正在对我的 C 项目运行代码质量检查,该项目涉及具有位域的结构。我遇到了一种情况,根据 MISRA C 2004 标准,规则 # 6.4 - 是一种违规行为,内容如下:
“6.4 位字段只能定义为 unsigned int 或 signed int 类型。”
Microsoft Developer Network 上可用的文献 here断言这一点。
谁能解释为什么位域成员的数据类型需要签名或无符号整数?为什么不允许我执行以下操作,即使以下代码编译时没有警告:
typedef struct
{
char a: 4;
char b: 4;
char flag: 1;
}MY_STRUCT
主要原因是,如果你不显式声明signed
或unsigned
,你不知道该类型是否会被视为signed
或 unsigned
除非阅读实现对它所做的定义。这意味着如果不使用带有显式符号关键字的类型,就无法编写可移植代码。 (还要注意,将 char
用于位域类型指示符是使用实现定义的类型。)
ISO/IEC 9899:2011 — §6.7.2.1 结构和 union 说明符
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 as int
,
then it is implementation-defined whether the bit-field is signed or unsigned.
指的是:
§6.7.2 类型说明符
¶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 as
signed int
or the same type as unsigned int
.