C language Union

Source: Internet
Author: User

C language Union
Meaning? A consortium is a memory area used for the structure of multiple variables. The value of the region is the value of the variable with the maximum length in the structure.

Union myunion {
Char charvar;
Int intvar;
Float floatvar;
}
Int main ()
{
Union myunion uni;
Printf ("enter a character ");
Scanf ("% C", & uni. charvar );
Printf ("the current characters in the Union myunion are % C/N", uni. charvar );
Printf ("enter an integer ");
Scanf ("% d", & uni. intvar );
Printf ("the current memory in the Union myunion is an integer % d/N", uni. intvar );
Printf ("enter a floating point number ")
Scanf ("% F", & uni. floatvar );
Printf ("the current floating point in the Union myunion is % F/N", uni. floatvar );
}

 

Consortium has some similarities with structure. But they are essentially different. In the structure, each member has its own memory space,
The total length of a structure variable is the sum of the member lengths. In "Union", members share a piece of memory space,
The length of a federated variable is equal to the longest length of each member. It should be noted that the so-called sharing here does not mean that multiple members are loaded into a joint variable at the same time,
This federated variable can be assigned to any member value, but only one value can be assigned at a time. If a new value is assigned, the old value is washed away. As described above,
If it is defined as a Union that can be attached to a "Class" or "Teaching and Research Section", an integer value (class) or a string (Teaching and Research Section) is allowed ). Either assign an integer value or a string, but not both. The definition of the Union type and the description of the Union variable must be defined,
Variables can be described as the Union type.

1. Definition of union

The general form of defining a union type is:

 
Union name
{
Member table
};
The member table contains several members. The general form of the members is: the name of the member name of the type specifier should comply with the requirements of the identifier.
For example:
Union perdata
{
Int
Class;
Char
Office;
};
Defines a union type named perdata, which contains two members, one is an integer, the member is a class, the other is a character array, and the array is named office. After joint definition, you can describe the joint variables. variables described as perdata types can be used to store integer classes or character arrays.

2. Description of Federated Variables

The description of Federated variables is the same as that of structural variables,
There are also three forms. That is, definitions are defined first and then explained. definitions are both described and directly described. Taking the perdata type as an example, it is described as follows:

Union perdata
{
Int
Class;
Char
Officae;
};
Union perdata A, B;
Or it can be described as follows:
Union perdata
{
Int class;
Char office;
} A, B;
Or it is directly described:
Union
{
Int class;
Char office;
} A, B
The variables A and B are of the perdata type. Their memory allocation is 7-8. The length of a and B variables should be equal to perdata.
Is equal
The length of the office array, which consists of 10 bytes. It can be seen that variables A and B use only two bytes for an integer value, and 10 bytes for a character array.

Assignment and use of joint Variables

Assign values to the federated variables only to the members of the variables. Federated variable Member: Federated variable name. member name
For example, after a is described as a variable of the perdata type, A. Class A. Office is not allowed to assign values or perform other operations only by using the joint variable name.
It is not allowed to initialize and assign values to the federated variables. The assignment can only be performed in the program? Why can't I find myself running? A federated variable,
Can only one member be assigned at a time? Route 8? The value of a federated variable is a member value of the federated variable.
[Example 7.15] There is a general table for teachers and students. The instructor data includes four items: name, age, occupation, and teaching and research section. There are four students: name, age, occupation, and class.
Program and input personnel data, and then output in a table.
[Code: 1: 8d8ee8c82c]
Main ()
{
Struct
{

Char name [10];

Int age;

Char job;

Union

{

Int class;

Char Office [10];

} Depa;

} Body [2];
Int N, I;

For (I = 0; I <2; I ++)
{

Printf ("input name, age, job and department/N ");

Scanf ("% S % d
% C ", body [I]. Name, & Body [I]. Age, & Body [I]. Job );


If (body [I]. Job ='s ')

Scanf ("% d", & Body [I]. Depa. Class );

Else

Scanf ("% s", body [I]. Depa. Office );
}

Printf ("name/Tage job class/office/N ");

For (I = 0; I <2; I ++)
{

If (body [I]. Job ='s ')

Printf ("% S/T % 3d % 3C % d/N", body [I]. Name, body [I]. Age
, Body [I]. Job, body [I]. Depa. Class );
Else

Printf ("% S/T % 3d % 3C % s/n", body [I]. Name, body [I]. Age,
Body [I]. Job, body [I]. Depa. Office );
}
}
[/Code: 1: 8d8ee8c82c]
In this example, a structure array body is used to store personnel data. The structure has four members. The member item Depa is a union type,
This union is composed of two members, one being an integer class and the other being a character array office. In the first for statement of the program, enter the data of the person, and enter the first three
Name, age, and job of the member, and then identify the member items of the job. For example, if it is "S", enter the class number (assigned to the student) for the combined Depa class. Otherwise, the Depa office will be lost.
(Assign the teaching and research group name to the teacher ).

When using scanf statements, note that any member of the array type, whether a structure member or a federated Member, cannot add the "&" operator before the entry. For example, in line 2 of the program

Body [I]. Name is an array type, and body [I]. Depa. Office in row 22nd is also an array type. Therefore, the "&" operator cannot be added between the two items. The second for statement in the program is used to output the values of each member item:

Summary of this Chapter

1.
Structure and union are two types of data. They are an important means for users to define new data types. There are many similarities between the structure and the Union, which are composed of members. Members can have different data types. The member representation is the same. Three methods are available for variable description.

2.
In the structure, each member occupies its own memory space and they exist at the same time. The total length of a structure variable is equal to the sum of all member lengths. In the Union, all Members cannot occupy the memory space at the same time, and they cannot exist at the same time. The length of the federated variable is equal to the length of the longest member.

3. "." is a member operator, which can be used to represent Member items. The member can also be expressed using the "->" operator.

4.
The structure variable can be used as a function parameter, and the function can also return a pointer variable pointing to the structure. Union variables cannot be used as function parameters, and functions cannot return pointer variables pointing to union. However, you can use a pointer to a federated variable or a federated array.

5. The structure definition can be nested, and the structure can also be associated as members to form the nesting of the structure and union.

 

//----------------------------------------------------------------------------

# Include
Union Myun
{
Struct
{
Int X;
Int y;
Int Z;
} U;
Int K;
};
Int main ()
{
A. U. x = 4;
A. U. Y = 5;
A. U. z = 6;
A. k = 0;
Printf ("% d/N", A. U. X, A. U. Y, A. U. z );
Return 0;
}

The description of Federated variables is the same as that of structural variables,
There are also three forms. Define
,
Further description
;
Description and direct description at the same time. To
Perdata
Type
,
Description:
:

Union perdata
{
Int class;
Char officae;
};
Union perdata A, B;
Or it can be both described
:

Union perdata
{
Int class;
Char office;
} A, B;
Or directly describe
:

Union
{
Int class;
Char office;
} A, B;

The Union type is shared memory, and the largest size structure is used as its own size.
In this case, the structure Myun contains the structure U, and the size is equal to the size of the structure U. In the memory, the Order x, y, and z are declared from low to high.
Then, when assigning values, in the memory, 4 is placed at the position of X, 5 is placed at the position of Y, 6 is placed at the position of Z, and K is now assigned, assign values to k because they are union and share memory, so they are placed from the first address of union.
The starting position of the first address is actually the position of X.
In this way, the position of X in the original memory is replaced by the value assigned by K, and the value is changed to 0. At this time, you need to print it, and you just need to check the memory, the position of X, that is, the position of K is 0, while the position value of Y and Z is not changed, so it should be 0, 5, 6

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.