Cprogramming 简明教程

Anonymous Structures and Unions in C

Anonymous Structures and Unions in C

anonymous structures and unions 的特性是在 C11 标准中引入的。其目的是增强 C 的灵活性和在某些情况下避免不必要的命名。

The feature of anonymous structures and unions was introduced in C11 standard. The aim was to enhance the flexibility of C and also to discard the need of superfluous naming in certain cases.

发现定义结构体和联合匿名化地极其有用,尤其是在涉及创建复杂数据结构的应用程序、硬件寄存器映射等中。这允许编写更直接且可读的代码。

The feature of defining struct and union anonymously has been found to be extremely useful, especially in applications involving the creation of complex data structures, hardware register mappings, etc. This allows for more straightforward and readable code.

Anonymous Structure

匿名结构体是一个没有标签或 typedefstructure definition 。它通常嵌套在另一个结构体内。

An anonymous structure is a structure definition without a tag or a typedef. It is usually nested within another struct.

Syntax for Anonymous Struct

以下是定义匿名结构体的语法 −

Here is the syntax of defining an anonymous structure −

struct type {
   elem1;
   elem2;
   struct {
      elem3;
      elem4;
   };
};

Access Members of Anonymous Structure

匿名 struct/union 的成员可以直接访问父 struct,从而简化了表示法。

Members of an anonymous struct/union can access the parent struct directly, simplifying the notation.

Example 1

在下面的代码中,我们定义了一个名为 employee 的结构体。在其中,一个匿名 struct 旨在保存员工的出生日期、月份和年份。在嵌套结构体的示例中,我们有一个内部的 dob 结构体。现在,我们将使用匿名 struct。

In the code below, we have defined a structure with the name as employee. Inside it, an anonymous struct is intended to hold date, month and year of birth of the employee. In the example on nested structure, we had an internal dob structure. Now we’ll use anonymous struct.

#include <stdio.h>

struct employee {
   char name[10];
   float salary;
   struct {
      int d, m, y;
   };
};

int main(){

   struct employee e1;
   strcpy (e1.name, "Kiran");
   e1.salary=25000;
   e1.d = 12;
   e1.m = 5;
   e1.y = 1990;

   printf("Name: %s\n", e1.name);
   printf("Salary: %f\n", e1.salary);
   printf("Date of Birth: %d-%d-%d\n", e1.d, e1.m, e1.y);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Name: Kiran
Salary: 25000.000000
Date of Birth: 12-5-1990

请注意,直接访问内部匿名 struct 的 "d"、"m" 和 "y" 元素。

Note that the "d", "m" and "y" elements of inner anonymous struct are accessed directly.

Example 2

在以下示例中,外部结构类型为 student ,它有一个嵌套的匿名结构来存储课程的标题和 ID。

The outer struct type in the following example is student, which has a nested anonymous struct to store the title and ID of the course.

#include <stdio.h>

struct student {
   char name[10];
   int age;
   struct {
      char coursettl[20];
      int courseid;
   };
};

int main(){

   struct student s1;
   strcpy (s1.name, "Kiran");
   s1.age = 27;
   strcpy(s1.coursettl, "C Programming");
   s1.courseid=1;

   printf("Name: %s\n", s1.name);
   printf("age: %d\n", s1.age);
   printf("Course Title: %s Course ID: %d\n", s1.coursettl, s1.courseid);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Name: Kiran
age: 27
Course Title: C Programming Course ID: 1

Anonymous Union

匿名联合是一种特殊类型的 union ,它没有名称。与普通联合不同,匿名联合主要用于创建可以无需联合名称直接访问的未命名成员。

An anonymous union is a special type of union that doesn’t have a name. Unlike regular unions, anonymous unions are primarily used to create unnamed members that can be accessed directly without qualifying them with a union name.

Syntax for Anonymous Union

以下是定义匿名联合的语法:

Here is the syntax of defining an anonymous union −

struct type {
   elem1;
   elem2;
   union {
      elem3;
      elem4;
   };
};

Access Members of Anonymous Union

匿名联合的成员可以无需使用联合名称直接访问。

The members of the anonymous union can be accessed directly without using a union name.

Example

匿名联合没有名称。元素共享相同的内存位置。

Anonymous unions do not have a name. The elements share the same memory location.

请看以下示例:

Take a look at the following example −

#include <stdio.h>

struct mystruct {
   int var;
   union {
      int var1;
      float var2;
      char var3;
   };
};

int main(){

   struct mystruct data;

   data.var = 10;
   data.var2 = 5.55;

   printf("mystruct.var: %d\n", data.var);
   printf("anonymous union elements: %d %f %c", data.var1, data.var2, data.var3);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

mystruct.var: 10
anonymous union elements: 1085381018 5.550000 �

Note :与普通联合类似,匿名联合变量的未初始化成员也会显示垃圾值。

Note: Like a regular union, the uninitialized members of an anonymous union variable also show garbage value.

Advantages of Anonymous Struct and Union

主要优点之一是无需任何内部结构或联合名称即可直接访问成员。这可以使代码更具可读性。以下是使用匿名结构和联合的一些其他优点:

One of the main advantages is the ability to access the members directly without any inner struct or union name. This can make the code more readable. Here is a list of some other advantages of using anonymous structures and unions −

  1. Memory Efficiency − Like regular unions, anonymous unions allow different data types to share the same memory space, leading to more memory-efficient code, especially useful in low-memory environments.

  2. Flexibility − Anonymous structures provide flexibility in how data is represented and accessed, allowing for more dynamic and versatile data structures.

  3. Convenience − This feature allows for a compact representation of a variable that can hold different data types.

  4. Ease of Initialization − They can be easier to initialize and use, as they do not require the declaration of a union variable.

请注意,在 C11 之前,匿名结构或联合类型不属于 C 标准。因此,如果目标系统使用符合早期标准的编译器,则在代码中使用它们会导致兼容性问题。

Note that anonymous struct or union types were not part of the C standard before C11. Hence, their use in the code may lead to compatibility problems, if the target system uses a compiler compliant with earlier standards.