- 匿名结构
- 嵌套实验
- 说明
- 常规用法
- 交流
匿名结构
匿名结构:在另一个结构中声明结构变量,而无需为其命名的嵌套结构称为匿名结构。
并且可以像访问包含结构中的成员一样访问匿名结构的成员。
嵌套实验
代码:
#include#include typedef union { struct { uint8_t C : 1; // Carry Bit uint8_t Z : 1; // Zero uint8_t I : 1; // Disable Interrupts uint8_t D : 1; // Decimal Mode (unused in this implementation) uint8_t B : 1; // Break uint8_t U : 1; // Unused uint8_t V : 1; // Overflow uint8_t N : 1; // Negative }; uint8_t self; } P_t; P_t P; int main(void) { printf("P size: %d Bytesn", sizeof(P)); P.C = 1; printf("C: %d, P: %dn", P.C, P.self); P.N = 1; printf("N: %d, P: %dn", P.N, P.self); return 0; }
输出:
P size: 1 Bytes C: 1, P: 1 N: 1, P: 129说明
- 嵌套在共用体中的结构体为匿名结构,可以直接访问其成员,比如 P.C、P.N 等;
- 该匿名结构体使用位域操作,每个成员仅占用一个位,共八个成员,故匿名结构体的大小为一个字节;
- 位域操作先定义的为低位,故 P.C 为 self 的 bit0 位,P.N 为 self 的 bit7 位,P.self = 0b1000 0001 = 129。
#include#include typedef union { struct option_n { uint8_t C : 1; // Carry Bit uint8_t Z : 1; // Zero uint8_t I : 1; // Disable Interrupts uint8_t D : 1; // Decimal Mode (unused in this implementation) uint8_t B : 1; // Break uint8_t U : 1; // Unused uint8_t V : 1; // Overflow uint8_t N : 1; // Negative }bit; uint8_t self; } P_t; P_t P; int main(void) { printf("P size: %d Bytesn", sizeof(P)); P.C = 1; printf("C: %d, P: %dn", P.bit.C, P.self); P.N = 1; printf("N: %d, P: %dn", P.bit.N, P.self); return 0; }
- 调用时多了一层 .bit;
- 结构体的 option_n 可以不写。
微信公众号:物联指北
B站:物联指北
千人企鹅群:658685162



