结论:位域的大小不能超过其类型的大小。例如,如果你的位域是 int 类型的,那么它的大小不能超过 int 类型的大小。在大多数平台上,int 类型的大小是 32 位。
在大多数平台上,int 类型的大小是 32 位。
6.4.1 bit-fields.c
#include <stdio.h>
struct bits // total: 9 bits
{
// unsigned a : 1;
// unsigned b : 3;
// unsigned c : 5;
int a : 1;
int b : 3;
int c : 28;
};
int main()
{
printf("Sizeof bits_var is: %lu", sizeof(struct bits));
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 输出:Sizeof bits_var is: 4 │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
#include <stdio.h>
struct bits // total: 9 bits
{
// unsigned a : 1;
// unsigned b : 3;
// unsigned c : 5;
int a : 1;
int b : 3;
int c : 29;
};
int main()
{
printf("Sizeof bits_var is: %lu", sizeof(struct bits));
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 输出:Sizeof bits_var is: 8 │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/