为什么 C 中的位域需要定义为 unsigned int 或 signed int 类型

为什么 C 中的位域需要定义为 unsigned int 或 signed int 类型

问题描述:

我正在对我的 C 项目运行代码质量检查,其中涉及带有位域的结构.我遇到了一种情况,根据 MISRA C 2004 标准,规则 #6.4 - 是违规行为,内容如下:6.4 位域只能定义为 unsigned int 或 signed int 类型."Microsoft Developer Network 上的可用文献此处 断言了这一点.谁能解释为什么位域成员的数据类型需要有符号或无符号整数?为什么我不允许执行以下操作,即使以下代码编译时没有警告:

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

主要原因是,如果您没有明确声明 signedunsigned,您就不会'不知道该类型是否会被视为 signedunsigned 除非通过阅读实现对其功能的定义.这意味着如果不使用带有显式签名关键字的类型,就无法编写可移植代码.(同样请注意,将 char 用于位域类型指示符是使用实现定义的类型.)

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.)

位域的类型应为 _Boolsigned intunsigned int 或某些的限定或非限定版本其他实现定义的类型.

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.

位域被解释为具有有符号或无符号整数类型,包括指定的位数.125)

A bit-field is interpreted as having a signed or unsigned integer type consisting of the specified number of bits.125)

125)如上面 6.7.2 中所述,如果使用的实际类型说明符是 int 或定义为 int 的 typedef-name,那么位域是有符号还是无符号由实现定义.

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.

指的是:

¶4 指定位域宽度的表达式应为整数常量表达式,其非负值不超过指定类型的对象的宽度(省略冒号和表达式).

¶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 ... 除了位域,说明符 int 是否指定与以下相同的类型是实现定义的signed int 或与 unsigned int 相同的类型.

¶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.