Why is Union invented in C different from struct?

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.