A summary of the Union usage in C language and C + + _c language

Source: Internet
Author: User

Start.

has been a long time no update, I am sorry to myself, even more sorry my dear readers, but also can not afford to start their own blog platform. Busy, too busy, busy looking for a job, find a good job, tangled in going to the big city, or return to the provincial capital city. Everyone is struggling with this problem and I hope you and I can discuss it. Other first, have been working so long, but also back to summing up the Union, indeed a bit too much, if and everyone said I have been engaged in the development of C + +, still do not know union, we may not really believe. Every day we are summing up those seemingly high-end things, what design patterns (of course I also have summed up), refactoring (I will also say later), but ignored those most basic, most fundamental knowledge points. Today, people ask me, I was blindfolded, so, I have this article.

What is Union?

The translation comes to say, is the common body, or also called the Commonwealth. When it comes to union, which is the common body, we have to say struct, when we have the following definition of struct:

Copy Code code as follows:

struct student
{
Char Mark;
Long num;
Float score;
};

With regard to the memory structure of the struct, it will be as shown in the following illustration (demonstrated on the x86 machine):

The value of sizeof (struct student) is 12bytes. However, when we define the union as follows,

Copy Code code as follows:

Union test
{
Char Mark;
Long num;
Float score;
};

The value of sizeof (union test) is 4. Why is that? That's what needs to be said. Sometimes, we need several different types of variables to exist in the same memory space, as above, we need to store a char type mark, a long type of num variable, and a float type score variable in the memory cell at the beginning of the same address. The above three variables, the char type and the long type occupy a different number of bytes of memory, but in union, they are all stored from the same address, that is, the coverage technology used, these three variables cover each other, and this makes several different variables share the same memory structure, called the "common body" The structure of the type. The union type defined above is structured as follows:

As mentioned above, the value of sizeof (union test) is 4. Then why is it 4? In general, the memory occupied by the structure struct is the sum of the memory occupied by each member (it also needs to consider the problem of memory alignment). And for union, in Tan Haoqiang's "C programming," it says: The union variable occupies a length of memory equal to the maximum length of the member's memory. Obviously, this is not true, for the size of the memory used by union, the problem of memory alignment needs to be considered. This is why the value of sizeof (union test) is 4.

Use Union in C

Say again good, more, after all is to be used in, the following is good to say C use Union. Like struct, union can only reference a common body variable before it is defined. And you cannot directly reference a shared body variable, only members in a shared-body variable. Just like the union test I defined above. We cannot refer directly to union as follows:

Copy Code code as follows:

Union test A;
printf ("%d", a);

This direct reference is wrong because there are several types of storage for a, which occupy different lengths of storage, and write only the common body variable name A, which makes it impossible for the compiler to determine the value of which member of the output. So, it should be written as follows:

Copy Code code as follows:

printf ("%d", A.mark);

At the same time, when using union, we also need to pay attention to the following points:

1. The same memory segment can be used to hold several different types of members, but at every moment only one of them exists, not several. That is, only one member at a time works, the other members do not work, that is, not both exist and work.

2. A member of the function in a common body variable is the last member to be deposited, and the original member loses its role after depositing a new member. For example, the following code:

Copy Code code as follows:

#include <iostream>
using namespace Std;

Union test
{
Char Mark;
Long num;
Float score;
}a;

int main ()
{
cout<<a<<endl; Wrong
A.mark = ' B ';
cout<<a.mark<<endl; Output ' B '
cout<<a.num<<endl; The acsii value of the 98 character ' B '
cout<<a.score<<endl; Output error value

A.num = 10;
cout<<a.mark<<endl; Output empty
cout<<a.num<<endl; Output 10
cout<<a.score<<endl; Output error value

A.score = 10.0;
cout<<a.mark<<endl; Output empty
cout<<a.num<<endl; Output error value
cout<<a.score<<endl; Output 10

return 0;
}

So, when using union, be Shipi careful.

3. The values of &a.mark, &a.num, and &a.score are the same because all the members ' starting addresses are the same in the Union.

4. The union variable cannot be used as a function parameter, and the function cannot be brought back to the union variable, but a pointer to a union variable can be used.

A 5.union type can appear in a struct type definition or a union array, whereas a struct can also appear in the union type definition, and an array can also be a member of a union.

Logically speaking, summed up here, the C language of the Union there is no more to say. But there is something called C + +, in which there is something called a class.

When union encounters an object

In the case of the Union in C alone, the summary above is sufficient, but now there is a thing called C + +; When the union encounters the object in C + +, everything becomes more and more messy. The Union usage rule summarized above is still applicable in C + +. Originally the union is from the C language, if we continue in C + + in the same way as the use of the Union, there is no problem. What if we put a class object in the Union? What's the result? For example, you have the following code:

Copy Code code as follows:

#include <iostream>
using namespace Std;

Class CA
{
int m_a;
};

Union Test
{
CA A;
Double D;
};

int main ()
{
return 0;
}

As you can see, there is no problem, and if we add a constructor to the class CA or add a destructor, we will find that the program is in error. Because things in the Union share memory, you cannot define static, reference-type variables. Because it is not allowed to hold objects of classes with constructors, destructors, and copy constructors in union, the corresponding class object pointers can be stored. The compiler cannot guarantee that the constructors and destructors of the class are called correctly, and thus a memory leak can occur. So, when we use Union in C + +, we try to keep the union style in the language, and try not to have the union with the object.

It's over.

We were all playing with those tall things, and looking back, we found another big pit behind. Open the dusty years of "C Language Program Design" (Tan Haoqiang), carefully wiped the cover of dust, thoughts immediately pulled back to freshman. Those years, my pure freshman. The longing for the university, the curiosity of the computer, the unknown to the programming, is this book, this damned "C language Programming", took me to the "program ape" this no way back. Said more, are tears, when you see this article, you should understand me. Codemonkey~~~, this way of no return, and the line and cherish.

= = = Modify Log = =

The

September 11, 2014 deletion of the text "cannot take the union variable as a function argument, nor can it bring the function back to the union variable, but you may use a pointer to a union variable." "Such a description, thank Cassie_lcy very much, but also in the comments attached to the verification code, very grateful, but also, I am very sorry, for this has not verified the knowledge, on the summary, to everyone caused a certain misleading, sorry." Must pay attention to the rigor of studying.

Related Article

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.