C 位域声明的异常语法
我遇到了一种我以前从未见过的位域语法C 位域声明的异常语法,c,gcc,C,Gcc,我遇到了一种我以前从未见过的位域语法 struct msg_hdr0{ uint8_t a : 1, b : 1, e : 4, f : 2;
struct msg_hdr0{
uint8_t a : 1,
b : 1,
e : 4,
f : 2;
};
int main(void)
{
struct msg_hdr0 hdr;
bzero((void *)&hdr, sizeof(hdr));
hdr.b = 1;
printf("hdr = 0x%X\n", *(uint32_t *)&hdr);
return 0;
}
这在linux和gcc编译器上运行良好。
有人能告诉我在哪里可以找到关于这个的文档吗。
这是GCC扩展吗
常用的位字段语法为:
struct box_props
{
unsigned int opaque : 1;
unsigned int fill_color : 3;
unsigned int : 4; // fill to 8 bits
unsigned int show_border : 1;
unsigned int border_color : 3;
unsigned int border_style : 2;
unsigned int : 2; // fill to 16 bits
};
标准
C99
第6.7.2.1节规定:
struct-declarator-list:
struct-declarator
struct-declarator-list , struct-declarator
struct-declarator:
declarator
declarator_opt : constant-expression
您可以使用,
将结构位字段成员声明为
struct msg_hdr0 {
uint8_t a : 1, b : 1, e : 4, f : 2;
};
对于如何使用位字段的问题,下面的代码可能会有所帮助。位字段是C语言中的标准字段,当不需要整数的整个大小来存储该值,并且特定数量的位足以保存该值时,可以使用该字段,这样可以节省内存,如下所示。另一个答案中已经有一个链接,关于为什么不使用位字段,但为了理解其目的是这样的
#include <stdio.h>
struct a
{
unsigned int a;
unsigned int b;
};
struct b
{
unsigned int a : 2; /* unsigned int a:2, */
/* b:3; */
unsigned int b : 3;
};
int main(void) {
struct b p;
p.a = 3; /* This member can hold just 2 bits */
p.b = 7;/* This member can hold just 3 bits */
printf("%d\n",sizeof(struct a)); /* Size of struct is 8 bytes */
printf("%d\n",sizeof(struct b)); /* size of struct is 4 bytes using bit fields*/
printf("%d\n",p.a);
printf("%d\n",p.b);
return 0;
}
#包括
结构a
{
无符号整数a;
无符号整数b;
};
结构b
{
无符号整数a:2;/*无符号整数a:2*/
/*b:3*/
无符号整数b:3;
};
内部主(空){
结构b-p;
p、 a=3;/*此成员只能容纳2位*/
p、 b=7;/*此成员只能容纳3位*/
printf(“%d\n”,sizeof(struct a));/*struct的大小为8字节*/
printf(“%d\n”,sizeof(struct b));/*使用位字段时,struct的大小为4字节*/
printf(“%d\n”,p.a.);
printf(“%d\n”,p.b.);
返回0;
}
在函数中,可以在单个语句或多个语句中声明变量列表
void myFunction(void)
{
// Declare several variables (of teh same type) in a single statement
int a, b, c;
// Declare some more, each in their own statement
int x;
int y;
int z;
}
类似地,结构中的位字段
struct myStruct
{
// Declare several bitfields in a single statement
int a : 1, b : 3, c : 4;
// Declare some more, each in their own statement
int x : 1;
int y : 3;
int z : 4;
}
位字段是标准C的一部分,因此任何关于该语言的好资源都应该提到它们。并不是说使用它们是一个问题,而是另一个问题。你基本上是告诉编译器有多少位与结构中的每个成员相关联,这样做你是在节省内存。你必须说
4*sizeof(int)=16个字节,而不使用位字段作为结构的大小,并且通过使用位字段,你只有8个字节作为结构的大小,因为整个结构(1+1+4+2)需要8个字节。你是指单行语法inta:1,b:2,c:3,与更常见的多行语法相比,inta:1;INTB:2;INTC:3代码>?查看上面的公共位字段语法,我只想知道新语法是从哪里来的。它是一些新的C标准的一部分,或者是GCC的扩展。@subbasish它是一个C标准。请查看C99
$6.7.2.1 ISO/IEC 9899:TC3。请参阅struct msg_hdr0
和struct box_props
。在句法上两者都是不同的。在struct msg_hdr0
中,我没有为每个变量输入uint8\u t,还使用逗号分隔每个变量。这个语法正确吗。@subbasish请注意这里的逗号运算符,它类似于inta,b,c代码>也可以写成inta:2,b:3代码>一点也不坏。这是个好问题。不过,现在您已经完成了“为什么我没有发现它?”例行程序,您可以稍微编辑一下标题。:-)(例如,“位域声明的异常语法”。)