The difference between Union and struct is:
1. For a union variable, all member variables share a piece of memory. The size of the memory is determined by the maximum length of these member variables.
2. The memory allocated by union is continuous, which is very important.
For more details, see the test.Code(Appendix 1 ):
Why do we need to invent union? This is determined by the Union feature, especially the second point above, because although the memory of the member variables in struct is independent, struct cannot guarantee that the allocated memory is continuous.
For example, the ax register of the CPU is divided into AH and Al. To assign a value to it, we can use Union:
Union _ ax_register {
Int I; // 4 bytes, union will allocate a 4-byte continuous memory
Unsigned short Ah; // 2 bytes
Unsigned short al; // 2 bytes
} Ax_register;
Now, if you assign a value to ax_register. I, The 16bit value will be assigned to Ah, And the 16bit value will be assigned to Al. Is it very convenient?
For another example, if we use Union to assign an int value to an IP address, we can assign a value to the four segments of the IP address at the same time. If struct is used, it will be a lot of trouble, as follows:
Union _ ip_address {
Int I; // spaceholder
Unsigned char ip_first_num;
Unsigned char ip_second_num;
Unsigned char ip_third_num;
Unsigned char ip_fourth_num;
} Ip_address;
In this way, if you assign a value to ip_address. I, The 8bit is automatically assigned to four IP fields. Is it convenient? It is more convenient to compare the size of the two IP addresses. it is OK to compare the int value.