例解 C 语言中的匿名联合体和匿名结构体

在 C 语言中,可以在结构体中声明某个联合体(或结构体)而不用指出它的名字,如此之后就可以像使用结构体成员一样直接使用其中联合体(或结构体)的成员。

下面是一段摘录自 msdn 对 anonymous structures 的解释

A Microsoft C extension allows you to declare a structure variable within another structure without giving it a name. 

These nested structures are called anonymous structures. C++ does not allow anonymous structures.

You can access the members of an anonymous structure as if they were members in the containing structure.

#include   
  
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   

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 

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 

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;
}


你可能感兴趣的:(other)