[rps-include post=6557]
[rps-include post = 6557]
Union is a data type used to store different type of variables. Union is very similar to the struct but have some differences those have explained below. Union can contain int,char,float,… etc. in a single block. One union can contain single set of data at a time.
联合是用于存储不同类型变量的数据类型。 联合与该结构非常相似,但是有一些区别,下面将对此进行说明。 联合可以在单个块中包含int,char,float等。 一个联合可以一次包含一组数据。
定义工会 (Defining Unions)
Defining union is very similar to struct. We will use union
statement. After union
statement we will put union tag. After the tag we can put variables in curly brackets. Union tag is optional. Union variables will be automatically instantiated.
定义联合与struct非常相似。 我们将使用union
声明。 在union
声明之后,我们将放置联合标记。 在标记之后,我们可以将变量放在大括号中。 联合标签是可选的。 并集变量将自动实例化。
union [union tag] {
member definition;
...
} [one or more union variables];
In this example we will define an union named MyData
and a variable mydata
.
在此示例中,我们将定义一个名为MyData
的联合和一个变量mydata
。
union MyData {
int count;
float range;
char name[20];
};
After union definition we should also initialize some variable which is in union MyData
type. We will initialize variable named mydata
在联合定义之后,我们还应该初始化一些union MyData
类型的变量。 我们将初始化名为mydata
变量
union MyData mydata;
访问成员 (Accessing Members)
In this part we will access to the union members by using the name of the union variable and the member name. We can use this method both set and get member data. We will put a point between the union variable name and union member name like below.
在这一部分中,我们将使用联合变量名称和成员名称访问联合成员。 我们可以使用此方法来设置和获取成员数据。 我们将在联合变量名称和联合成员名称之间添加一个点,如下所示。
mydata.count = 10;
Below we can see an example where member variables data is set and get.
下面我们可以看到一个设置和获取成员变量数据的示例。
#include <stdio.h>
#include <string.h>
union MyData {
int count;
float range;
char name[20];
};
int main( ) {
union MyData mydata;
mydata.count = 10;
mydata.range = 220.5;
strcpy( mydata.name, "C Programming");
printf( "mydata.count : %d\n", mydata.count);
printf( "mydata.range : %f\n", mydata.range);
printf( "mydata.name : %s\n", mydata.name);
return 0;
}
结构与联合 (Structures vs Unions)
As stated previously struct and union have syntax similarities. But the biggest difference is struct variables holds their members in separate memory areas but all same union variables will hold same memory areas. Simply single union type will hold single data for all union variables for the same type.
如前所述,struct和union具有语法相似性。 但是最大的区别是结构变量将其成员保存在单独的存储区中,但是所有相同的并集变量将保存相同的存储区。 单个联合类型将仅包含同一类型的所有联合变量的单个数据。
[rps-include post=6557]
[rps-include post = 6557]