C++ Union structure
Angie An

C++ The union Data Structure

A union is like a struct in that it generally has several fields, all of which are public by default. Unlike a struct, however, only one of the fields is used at any given time.

In other words, it is a structure that allows the same storage space to be used to store values of different data types at different times.

Unions can be used to conserve memory when a structure is needed in which several pieces of information of different types must be represented but only one will be used at a time, as when the components of a container must contain values of differing data types.

The usual syntax for a union is illustrated by

1
2
3
4
5
6
7
8
union Test{
struct{
int x;
int y;
int z;
}s;
int k;
}myUnion;
1
2
3
4
5
6
7
8
9
10
11
int main()
{
myUnion.s.x = 4;
myUnion.s.y = 5;
myUnion.s.z = 6;
myUnion.k = 0;
cout<< myUnion.s.x <<endl;
cout<< myUnion.s.y <<endl;
cout<< myUnion.s.z <<endl;
cout<< myUnion.k <<endl;
}

When the above code is executed, the program will output the following result

1
2
3
4
0
5
6
0

对k的赋值因为是union,要共享内存,所以从union的首地址开始放置,首地址开始的位置其实是x的位置,这样原来内存中x的位置就被k所赋的值代替了,就变为0了。

And this is basically how union works.

 Comments