在 C 语言中,可以在结构体中声明某个联合体(或结构体)而不用指出它的名字,如此之后就可以像使用结构体成员一样直接使用其中联合体(或结构体)的成员。
#include <stdio.h>
struct person
{
char *name;
char gender;
int age;
int weight;
struct
{
int area_code;
long phone_number;
};
};
int main(void)
{
struct person jim = {"jim", 'F', 28, 65, {21, 58545566}};
printf("%d\n", jim.area_code);
}
如果不使用匿名结构体,则上述例子对应的代码如下:
#include <stdio.h>
struct phone
{
int area_code;
long phone_number;
};
struct person
{
char *name;
char gender;
int age;
int weight;
struct phone office;
};
int main(void)
{
struct person jim = {"jim", 'F', 28, 65, {21, 58545566}};
printf("%d\n", jim.office.area_code);
}
对比上述两个例子可以看出:
使用匿名结构体,结构体对象 jim 可以通过 jim.area_code 直接访问匿名结构体成员变量 area_code,代码相对比较简洁
反之则必须通过 jim.office.area_code 来访问结构体成员变量
匿名联合体举例如下:
#include <stdio.h>
struct person
{
char *name;
union
{
char gender;
int id;
};
int age;
};
int main(void)
{
struct person jim = {"jim", 'F', 28};
printf("jim.gender = %c, jim.id = %d\n", jim.gender, jim.id);
return 0;
}
如果不适用匿名联合体,那么程序如下:
#include <stdio.h>
union u
{
char gender;
int id;
};
struct person
{
char *name;
union u test;
int age;
};
int main(void)
{
struct person jim = {"jim", 'F', 28};
printf("jim.test.gender = %c, jim.test.id = %d\n", jim.test.gender, jim.test.id);
return 0;
}
————————————————
keil也支持匿名结构体、联合体
#pragma anon_unions
typedef union {
unsigned int num;
struct {
unsigned int nLow :8;
unsigned int nHigh :8;
};
}kkTypedef;
void jjj(void)
{
kkTypedef kknum;
kknum.num=99;
kknum.nLow=10;
}
//keil中默认是不支持匿名结构体的,需要编译指令#pragma anon_unions指名。
但是不支持这样的匿名结构体
#pragma anon_unions
union {
unsigned int num;
struct {
unsigned int nLow :8;
unsigned int nHigh :8;
};
};
void jjj(void)
{
num=99;
nLow=10;
}
error: #20: identifier "num" is undefined
error: #20: identifier "nLow" is undefined
但在IAR里是可以的,有点不一样。
补充:好像在GCC编译器中也是可以的。
补充2:在CCS V5.1中使用MSP430中不能使用以上两个结构体,不知道在CCS V5.1中MSP430的编译器是什么,反正是不支持匿名结构体。
————————————————