位段以位為單位定義結構體成員佔用空間,既能節省空間,又方便位元操作。含位段的結構稱為位段結構。
type [var]: digits
type:僅限 int、unsigned int、signed intvar:可選,可省略(無名位段)digits:佔用二進制位數struct node {
unsigned int a:4; // 位段 a,佔 4 位
unsigned int :0; // 無名位段,佔 0 位(強制對齊)
unsigned int b:4; // 位段 b,佔 4 位
int c:32; // 位段 c,佔 32 位
int :6; // 無名位段,佔 6 位
};
int、unsigned int、signed intint 32 位)&)int/unsigned inttypedef struct { unsigned int a:1; } S; // 4 Bytes
typedef struct { unsigned int :0; } S1; // C:0, C++:1
typedef struct { unsigned int a:1; unsigned int :0; unsigned c:32; } S2; // 8 Bytes
typedef struct { unsigned int a:4; unsigned int :0; int :6; unsigned c:32; } S3; // 12 Bytes
typedef struct { unsigned int a:1; char b; int c:1; int d:2; unsigned int e:2; } S4; // 4 Bytes
1 -1 -2 3
4 1 8 12 4
c 只有 1 位(符號位),賦 1 後符號擴展為 -1d 佔 2 位,賦 2(二進制 10)符號擴展為 0xFFFFFFFE = -2:0 強制換到下一儲存單元