C Language Common Body (Union) detailed and sample code _c language

Source: Internet
Author: User

In the previous tutorial, we know that a struct (Struct) is a constructed type or a complex type that can contain multiple types of members. In C, there is another syntax that is very similar to a struct, called a common body (Union), which is defined in the following format:

Union shared body Name {
Member List
};

A common body is sometimes called a union or a consortium, which is also the meaning of the word Union.

The difference between a struct and a common body is that each member of the structure occupies different memory and has no effect on each other, while all members of the shared body occupy the same memory, and modifying a member affects all remaining members.

The structure occupies more memory than equals the sum of memory that is occupied by all members (there may be gaps between members), and the total memory consumed by the shared body equals the memory occupied by the longest member. The shared body uses a memory overlay technique that can only hold the value of one member at a time, and if the new member is assigned a value, the value of the original member is overwritten.

A common body is also a custom type that you can use to create variables, such as:

Union data{
 int n;
 char ch;
 Double F;
};
Union data A, B, C;

The above is to define a common body, create a variable, or create a variable while defining a common body:

Union data{
 int n;
 char ch;
 Double F;
} A, B, C;

If you no longer define a new variable, you can also omit the name of the shared body:

Union data{
 int n;
 char ch;
 Double F;
} A, B, C;

In the common body data, member F occupies up to 8 bytes of memory, so variables of type data (i.e. A, B, C) also occupy 8 bytes of memory, see the following demo:

#include <stdio.h>
Union data{
 int n;
 char ch;
 Short m;
};
int main () {
 Union data A;
 printf ("%d,%d\n", sizeof (a), sizeof (Union data));
 A.N = 0x40;
 printf ("%x,%c,%hx\n", A.N, a.ch, a.m);
 a.ch = ' 9 ';
 printf ("%x,%c,%hx\n", A.N, a.ch, a.m);
 a.m = 0x2059;
 printf ("%x,%c,%hx\n", A.N, a.ch, a.m);
 A.N = 0x3e25ad54;
 printf ("%x,%c,%hx\n", A.N, a.ch, a.m);
 
 return 0;
}

Run Result:

4, 4
40, @, 40
39, 9, 39
2059, Y, 2059
3e25ad54, T, AD54

This code verifies not only the length of the shared body, but also the interaction between the members of the shared body, and the modification of a member's value affects other members.

To understand the output above and figure out how members interact with each other, you have to understand how each member is distributed in memory. Take the above data as an example, the individual members are distributed in memory as follows:

Members N, CH, m are "aligned" to one end in memory, the CH assignment modifies the previous byte, and the M assignment modifies the first two bytes, and all bytes are modified for n assignment. That is, CH and M affect part of n data, and n affects all of the data for CH and M.

The above figure is on the vast majority of PC computer memory distribution, if it is 51 SCM, the situation will be different:

Why do different machines have different distributions? This is related to the storage mode of the machine, and we will explore it in the VIP tutorial "big end Small and discriminant way" section.

Application of common-use body

The common body is used less in the general programming, and it is used more in the single-chip microcomputer. For PCs, one example that is often used is: a table with information about students and teachers. Student information includes name, number, sex, occupation, score, teacher's information including name, number, gender, occupation, teaching subjects. Take a look at the table below:


Name
Num
Sex
Profession
Score/course
Hanxiaoxiao
501
F
S
89.5
Yanweimin
1011
M
T
Math
Liuzhentao
109
F
T
中文版
Zhaofeiyan
982
M
S
95.0

F and M are respectively female and male, s represents student, T represents teacher. As you can see, the data that students and teachers contain are different. Now you need to put this information in the same table and design the program to enter the personnel information and then output it.

If everyone's information is treated as a structural variable, then the first 4 member variables of the teacher and student are the same, and the 5th member variable may be score or course. When the value of the 4th member variable is s, the 5th member variable is score, and when the value of the 4th member variable is T, the 5th member variable is course.

With the above analysis, we can design a structure that contains a common body, see the following code:

#include <stdio.h> #include <stdlib.h> #define TOTAL 4//headcount struct{char name[20];
 int num;
 char sex;
 char profession;
  union{float score;
 Char course[20];
} SC;
} Bodys[total];
 int main () {int i;
  Enter personnel information for (i=0 i<total; i++) {printf ("Input info:");
  scanf ("%s%d%c%c", Bodys[i].name, & (Bodys[i].num), & (Bodys[i].sex), & (Bodys[i].profession));
  if (bodys[i].profession = = ' s ') {//If it is a student scanf ("%f", &bodys[i].sc.score);
  }else{//If the teacher scanf ("%s", Bodys[i].sc.course);
 } fflush (stdin);
 ///Output person information printf ("\nname\t\tnum\tsex\tprofession\tscore/course\n"); For (i=0 i<total; i++) {if (bodys[i].profession = = ' s ') {//If the student is printf ("%s\t%d\t%c\t%c\t\t%f\n", Bodys[i].name, Bo
  Dys[i].num, Bodys[i].sex, Bodys[i].profession, Bodys[i].sc.score); }else{//If the teacher is printf ("%s\t%d\t%c\t%c\t\t%s\n", Bodys[i].name, Bodys[i].num, Bodys[i].sex, Bodys[i].profession, Bodys
  [I].sc.course);
} return 0;
 }

Run Result:

Input Info:hanxiaoxiao 501 F S 89.5↙
Input info:yanweimin 1011 M T Math↙
Input Info:liuzhentao 109 F t English↙
Input Info:zhaofeiyan M S 95.0↙

Name Num Sex Profession Score/course
Hanxiaoxiao 501 F S 89.500000
Yanweimin 1011 m T Math
Liuzhentao 109 F t 中文版
Zhaofeiyan M S 95.000000

The above is the C language common body of data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

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.