位域

基本类型 / 数字 / 整型

//the number after the colon is the width of the field in bits
struct Date {
    unsigned day   : 5;  //0..31
    unsigned month : 4;  //0..15
    unsigned year  : 12; //0..4095
};

struct Date date = {.day = 30, .month = 9, .year = 2026};
//date is 30.9.2026

//the fields share one unsigned instead of three
size_t size = sizeof(struct Date);
//size is 4

//a value that does not fit keeps only the low bits
struct Date wrong = date;
unsigned month = 17;
wrong.month = month;
//wrong.month is 1 (17 is 10001, four bits keep 0001)

//a field has no address: &date.day is an error;
//the order of the bits in memory depends on the compiler

printf("date is %u.%u.%u\n", date.day, date.month, date.year);
printf("size is %zu\n", size);
printf("wrong.month is %u\n", wrong.month);