C语言位域 #

一、位域概述 #

1.1 什么是位域 #

位域允许按位分配存储空间,节省内存。

1.2 定义语法 #

c
struct {
    类型 成员名 : 位数;
};

二、位域定义 #

2.1 基本示例 #

c
#include <stdio.h>

struct Flags {
    unsigned int a : 1;
    unsigned int b : 2;
    unsigned int c : 3;
};

int main() {
    struct Flags f = {1, 2, 5};
    
    printf("a = %u\n", f.a);
    printf("b = %u\n", f.b);
    printf("c = %u\n", f.c);
    printf("结构体大小: %zu\n", sizeof(f));
    return 0;
}

2.2 应用场景 #

c
#include <stdio.h>

struct Date {
    unsigned int day : 5;
    unsigned int month : 4;
    unsigned int year : 12;
};

int main() {
    struct Date date = {31, 12, 2024};
    printf("日期: %u-%u-%u\n", date.year, date.month, date.day);
    return 0;
}

三、注意事项 #

  • 位域不能取地址
  • 位域顺序依赖实现
  • 注意溢出

四、总结 #

要点 说明
定义 类型 成员 : 位数
用途 节省内存
限制 不能取地址

下一步,让我们学习typedef!

最后更新:2026-03-26