Further understanding of union and some deep applications

Source: Internet
Author: User
Although union is rarely used during program development ,When I first learned C language ,The Union chapter was skipped by the teacher. ,Although ,I think my understanding of union is sufficient. ,However ,After finishing the previous article <(David's Reading Notes )C ++Thoughts on using Union in >After ,The discussion on the Internet drove me to pay attention to this basic language feature. ,And written in this article .

The following starts with the Union overview in msdn.,It seems boring.,However,Sometimes reading specification can give us a lot of tips.,When we focus on one thing from the application perspective,Many deeper considerations are ignored..So,Let's take a look.,Something in it may have been ignored by you..

Union
Union[Tag] {Member-List}[Declarators];

[Union]Tag declarators;

The Union keyword declares a union type and/Or a variable of a union type.

A union is a user-Defined data type that can hold values of different types at different times.It is similar to a structure
Before t that all of its Members start at the same location in memory.A union variable can contain only one of its members
A time.The size of the Union is at least the size of the largest member(David note:I cannot figure out a situation larger).

For related information,See Class,Struct,And anonymous Union.

Declaring a union

Begin the declaration of a union with the Union keyword,And enclose the member list in curly braces:

Union unknown// Declare union type
{
Char ch;
Int I;
Long L;
Float F;
Double D;
}
Var1;// Optional declaration of Union variable
Using a union

A c++Union is a limited form of the class type.It can contain access specifiers(Public,Protected,Private),Member Data,
And member functions,Including constructors and Destructors.It cannot contain virtual functions or static data members.It
Cannot be used as a base class,Nor can it have base classes.Default access of members in a union is public.

A c union type can contain only data members.

In C,You must use the Union keyword to declare a union variable.In C++,The Union keyword is unnecessary:

Example 1

Union unknown var2;// C declaration of a Union variable
Unknown var3;// C ++ declaration of a Union variable
Example 2

A variable of a union type can hold one value of any type declared in the Union.Use the Member-Selection Operator(.)To access a member of a union:

Var1.I=6;// Use variable as integer
Var2.D=5.327;// Use variable as double

To avoid slight distortion of the above text,I did not translate it,However, I would like to summarize it here:
1. Union is a special type of struct./Class,Is a type that can be used to accommodate multiple types,But with struct/The difference between classes is that,All member variables share the same bucket(The maximum size of the member type),This makes it changeable.,You can switch between different members at will.,Without the need for forced type conversion,But this also makes it impossible for you to modify it as a member variable without affecting another member variable.;
2. Union can also be constructed./Destructor,It can also contain an access identifier.,But cannot contain virtual functions or static member variables/Method.

Notes for using Union,Refer to my previous article: <(David's Reading Notes)C++Thoughts on using Union in>.
Next we will talk about some interesting and meaningful Union applications..
1. in_addr

Struct in_addr{
Union{
Struct{U_char s_b1,S_b2,S_b3,S_b4;}S_un_ B;
Struct{U_short s_w1,S_w2;}S_un_w;
U_long s_addr;
}
S_un;
};

For the above struct,The person who wrote the Socket Application,I must have used it..I wonder if you have noticed that,It contains an interesting Union,Each member of the Union has the same size.,Different representations of the same information.You can also use this feature to provide different representations of the same information during programming.,Note that,Cross-platform applications,The Influence of byte order may cause unnecessary troubles for you..

2. Anonymous Union
Anonymous Union is a Union without a name or declaration list.,This is not the same as '_ unnamed' union.,Its declaration form is as follows::
Union{Member-List};

Anonymous union only notifies the compiler that its member variables share an address.,Variables are directly referenced.,Do not use the common dot operator syntax.That's why,Anonymous union has the same scope level as other variables in the same program block.,Note the naming conflict..
See the following example.:

# Include <iostream. h>

Struct dataform
{

Enum datatype{Chardata=1,Intdata,Stringdata};
Datatype type;

// Declare an anonymous union.
Union
{

Char chcharmem;
Char*Szstrmem;
Int iintmem;
};

Void print();
};

Void dataform::Print()
{

// Based on the type of the data, print
// Appropriate data type.
Switch(Type)
{

Case chardata:
Cout<Chcharmem;
Break;
Case intdata:
Cout<Szstrmem;
Break;
Case stringdata:
Cout<Iintmem;
Break;
}
}

In addition,Anonymous Union also has the following constraints::
1).The vertex operator is not used for anonymous union.,Therefore, the elements contained in the anonymous union must be data.,Member functions are not allowed.,It cannot contain private or protected members.;
2).The global anonymous union must be static.(Static)Otherwise, it must be placed in an anonymous namespace..

Notes:
Concept of anonymous Union,You may be unfamiliar,However, developers of Windows Applications,There is a frequently used structure that includes anonymous union.,It is variant.,Maybe you didn't pay attention to it.:

Typedef struct farstruct tagvariant Variant;
Typedef struct farstruct tagvariant variantarg;

Typedef struct tagvariant{
Vartype vt;
Unsigned short wreserved1;
Unsigned short wreserved2;
Unsigned short wreserved3;
Union{
Byte bval;// Vt_ui1.
Short ival;// Vt_i2.
Long lval;// Vt_i4.
Float fltval;// Vt_r4.
//...
};
};

3. type conversion using Union
As mentioned earlier,Union is changeable.,You can switch between different members at will.,Without the need for forced type conversion,The following is an example.(Actually, 1 has already explained this well.):

# Include <iostream>
Using namespace std;

Struct data
{

Char C1;
Char C2;
};

Int main()
{

Union{ 
Int I; 
Data data;
}
_ UT;

_ UT.I=Zero X 6162;

Cout<"_ Ut. Data. C1 ="<_ UT.Data.C1<Endl
<
"_ Ut. Data. C2 ="<_ UT.Data.C2<Endl;

Return 0;
}

Yes,Data Type Conversion,Not Union expertise,It's just a usable feature..Because,Inter-type conversion using union is easily affected by the Platform,The above program uses Intel x86+Windows 2000+When vc6 is used, the output is:
_ UT.Data.C1=B
_ UT.Data.C2=A
(
Note:Because Intel CPU architecture is little endian)
On Sun's,The result you get is:
_ UT.Data.C1= 
_ UT.Data.C2=
(
Note:Because when using big endian,The first two bytes are 0x0000.)

Even on the same platform,Do not use Union when converting integer and real types.,Otherwise,You will get an inexplicable conclusion.(This is because the CPU processes the real type.,This method varies greatly from platform to platform.,At the same time,According to C++Standard,This will cause "undefined behavior").

About using references for type conversion,See<Application of reference in forced type conversion>.

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.