What is the method of initializing a union in the C lan…
In C language, there are two ways to initialize a union:
- Initialization using member names: You can use member names to initialize specific members of a union. This method requires the use of the member name and an equal sign to specify the initialized member.
Here is an example code:
union MyUnion {
int a;
float b;
};
int main() {
union MyUnion u1 = {.a = 10}; // 使用成员名初始化
union MyUnion u2 = {.b = 3.14f};
return 0;
}
In this example, the members a and b are used to initialize the members of unions u1 and u2 respectively.
- Initialize with position: Alternatively, members of the union can be initialized using their positions. This method involves providing initialization values in the order in which the members are declared in the union.
Here is the sample code:
union MyUnion {
int a;
float b;
};
int main() {
union MyUnion u1 = {10}; // 使用位置初始化
union MyUnion u2 = {3.14f};
return 0;
}
In this example, the values for initialization are provided in order of the members without the need for using member names.
Regardless of the method used, only one member of the union will be initialized, while the others will be set to undefined values.