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

标签 c structure bit-fields

<分区>

我正在对我的 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

最佳答案

主要原因是,如果你不显式声明signedunsigned,你不知道该类型是否会被视为signedunsigned 除非阅读实现对它所做的定义。这意味着如果不使用带有显式符号关键字的类型,就无法编写可移植代码。 (还要注意,将 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.

关于c - 为什么 C 中的位域需要定义为 unsigned int 或 signed int 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23987376/

相关文章:

在位域结构上转换字节序(再次)

C: 如何多次使用相同的 char* [] 而不更改已经设置的值?

c - 程序经过镜像功能后重印图像

c - 这个C union 的成员有什么区别吗?

c - C 中的重叠位域

c - 将文件中的整数数组存储在结构 C 中

c - F77 中的不透明指针

c - 语义版本控制 : minor or major change?

c - 这个汇编语句是什么意思?

c - wcscoll 函数被标记为中毒,我该怎么办?